Selenium使用Python自动单击选项卡

2024-09-30 02:34:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Selenium和Python来创建一个包含JavaScript的网页。 页面顶部的赛马场结果选项卡,如“Ludlow”、“Dundalk”,可以手动单击,但没有任何明显的超链接。 ... 从selenium导入webdriver 从selenium.webdriver.common.keys导入密钥 从selenium.webdriver.support.ui导入WebDriverWait 从selenium.webdriver.common.by导入 从selenium.webdriver.support将预期的_条件导入为EC

driver = webdriver.Chrome(executable_path='C:/A38/chromedriver_win32/chromedriver.exe')

driver.implicitly_wait(30)
driver.maximize_window()
# Navigate to the application home page
driver.get("https://www.sportinglife.com/racing/results/2020-11-23")

到目前为止,这是可行的。我使用BeautifulSoup查找新GenericTab的标签名称,例如“Ludlow”、“Dundalk”等。但是,下面的代码试图自动单击选项卡,每次都会超时

WebDriverWait(driver, 60).until(EC.element_to_be_clickable((By.LINK_TEXT, "Ludlow"))).click()

欢迎任何帮助


Tags: to网页supportdriverseleniumcommonjavascriptchromedriver
1条回答
网友
1楼 · 发布于 2024-09-30 02:34:38

WebElement不是<a>标记,而是<span>标记,因此By.LINK_TEXT不起作用

要单击所需的元素,可以使用以下基于Locator Strategies中的任意一个:

  • 卢德洛

    driver.get("https://www.sportinglife.com/racing/results/2020-11-23")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@mode='primary']"))).click()
    driver.find_element_by_xpath("//span[@data-test-id='generic-tab' and text()='Ludlow']").click()
    
  • 灌篮

    driver.get("https://www.sportinglife.com/racing/results/2020-11-23") 
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@mode='primary']"))).click()  
    driver.find_element_by_xpath("//span[@data-test-id='generic-tab' and text()='Dundalk']").click()
    

理想情况下,单击需要为element_to_be_clickable()诱导WebDriverWait的元素,可以使用以下基于Locator Strategies

  • 卢德洛

    driver.get("https://www.sportinglife.com/racing/results/2020-11-23")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@mode='primary']"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@data-test-id='generic-tab' and text()='Ludlow']"))).click()
    
  • 灌篮

    driver.get("https://www.sportinglife.com/racing/results/2020-11-23") 
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@mode='primary']"))).click()  
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@data-test-id='generic-tab' and text()='Dundalk']"))).click()
    
  • 注意:您必须添加以下导入:

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

相关问题 更多 >

    热门问题