簡體   English   中英

Python selenium find_element_by_xpath 在頁面中找不到現有元素

[英]Python selenium find_element_by_xpath not finding existing element in page

我正在使用 Python 3.6+ 和 Selenium 3.141

我試圖從頁面中獲取一個元素,盡管我使用了正確的 Xpath 表達式(在瀏覽器控制台中確認),但相同的 Xpath 表達式在 Z8E00596AD8DE2213FF8ZDchrome 驅動程序中引發了“NotFound”錯誤。

我的腳本.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? 我該如何解決?

點擊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

頁面源中缺少必需的內容 - 它是動態加載的,因此您需要等到它出現在 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]')))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM