【问题标题】:Python selenium find_element_by_xpath not finding existing element in pagePython selenium find_element_by_xpath 在页面中找不到现有元素
【发布时间】:2021-03-08 11:29:09
【问题描述】:

我正在使用 Python 3.6+ 和 Selenium 3.141

我正在尝试从页面中获取元素,虽然我使用了正确的 Xpath 表达式(在浏览器控制台中确认),但相同的 Xpath 表达式在 selenium chrome 驱动程序中引发了“NotFound”错误。

myscript.py

​​>
from selenium import webdriver


url = 'https://live.euronext.com/en/product/stock-options/AH1-DPAR'
browser = webdriver.Chrome(executable_path='./chromedriver')
browser.get(url)

try:
    
    checkbox = browser.find_element_by_xpath('//*[@id="form-options-index"]/div/div[2]')
    
except:
    pass

脚本会在调用 find_element_by_xpath() 方法时引发异常 - 即使在使用浏览器时,相同的 Xpath 表达式也会导致正确识别/选择元素。

为什么 Xpath 表达式不适用于 selenium?我该如何解决这个问题?

【问题讨论】:

    标签: python selenium xpath


    【解决方案1】:

    页面源中缺少必需的内容 - 它是动态加载的,因此您需要等到它出现在 DOM 中:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    url = 'https://live.euronext.com/en/product/stock-options/AH1-DPAR'
    browser = webdriver.Chrome(executable_path='./chromedriver')
    browser.get(url)
    
    checkbox = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="form-options-index"]/div/div[2]')))
    

    【讨论】:

      【解决方案2】:

      点击Select all复选框。使用WebDriverWait() 并等待element_to_be_clickable() 并关注Xpath

      WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="form-options-index"]//label[@for="select_all_dates"]'))).click()
      

      您需要导入以下库。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多