我是 Selenium 的新手,我有興趣使用它的功能打開一堆文本檔案,以獲取
uj5u.com熱心網友回復:
driver.get()在回傳之前不等待 AJAX 請求完成。您嘗試單擊的元素是通過 AJAX 請求創建的,并且在您嘗試單擊它時還不存在。
要解決此問題,您必須首先等待創建元素,如以下代碼所示。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Firefox(executable_path='xxx/geckodriver.exe'))
driver.get('https://mymarketnews.ams.usda.gov/viewReport/2837')
WebDriverWait(driver, timeout=10).until(EC.presence_of_element_located((By.ID, '2020s')))
elt = driver.find_element(By.XPATH, '//*[@id="2020s"]/a')
elt.click()
當您繼續從事這個專案時,還有兩件事需要注意:
- CSS 選擇器有一個限制,它們不能用于查找 ID 以數字開頭的元素。
- 您需要直接單擊 <a> 元素,而不是它周圍的 <li> 元素。
uj5u.com熱心網友回復:
嘗試使用這個 CSS 選擇器:
"#2020s > a"
或 Xpath
"//*[@id='2020s']/a"
也嘗試添加一些等待之后driver.get()
https://selenium-python.readthedocs.io/waits.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/436006.html
上一篇:如果CONDITION在Recaptcha和另一個元素之間不起作用,則只有1個起作用。硒蟒
下一篇:Selenium找不到表
