Using Selenium in Python, how do I click a link that is different for each item in a list?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 06:17:44

问题


Iam using selenium in python and trying click on a link however its different for every item in a list. How do I click the link below if changes each hour?

<td class="name table-participant" colspan="2"><a 
href="/basketball/europe/euroleague/lyon-villeurbanne-alba-berlin- 
vcATLt3c/"><span class="bold">Lyon-Villeurbanne</span> - Alba 
Berlin</a></td>

driver = webdriver.Chrome()
driver.implicitly_wait(2)
driver.maximize_window()
driver.get("https://www.oddsportal.com")

elem = driver.find_element_by_link_text('BASKETBALL')
elem.click()
sleep(2)
elem1 = driver.find_element_by_link_text('Europe')
elem1.click()
sleep(2)
elem2 = driver.find_element_by_link_text('Euroleague')
elem2.click()
sleep(2)
elem3 = driver.find_element_by_link_text('RESULTS')
elem3.click()
sleep(2)

elem4 = driver.find_elements_by_xpath("td/a href[contains(text(), '/basketball/europe/euroleague/')]")
#WebDriverWait(driver,10).until(EC.presence_of_all_elements_located((By.XPATH("//li[contains(., '/basketball/europe/euroleague/')"))))
elem4.click()

回答1:


Induce WebDriverWait() and visibility_of_all_elements_located() and following CSS selector to get all the elements in result table.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver=webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.oddsportal.com")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.LINK_TEXT,"BASKETBALL"))).click()
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.LINK_TEXT,"Europe"))).click()
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.LINK_TEXT,"Euroleague"))).click()
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.LINK_TEXT,"RESULTS"))).click()

#To get all the elements
allelements=WebDriverWait(driver,15).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,"td.name.table-participant >a[href^='/basketball/europe/euroleague/']")))

for i in range(len(allelements)):

    #To avoid stale exceptions
    allelements = WebDriverWait(driver, 15).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "td.name.table-participant >a[href^='/basketball/europe/euroleague/']")))
    print(allelements[i].text)
    #To avoid ElementClickInterceptedException 
    driver.execute_script("arguments[0].click();",  allelements[i])
    #Perform your opearions
    driver.back()


来源:https://stackoverflow.com/questions/59433697/using-selenium-in-python-how-do-i-click-a-link-that-is-different-for-each-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!