【发布时间】:2019-02-01 16:43:01
【问题描述】:
我目前正在尝试做一些 Selenium 网页抓取,但我一直遇到这个错误:
StaleElementReferenceException:消息:过时的元素引用: 元素未附加到页面文档
代码应该在http://www.grownjkids.gov/ParentsFamilies/ProviderSearch 上不断单击结果的下一个按钮 (">") 并从循环中的每个页面抓取结果。它会在几个页面上正确执行此操作,但会偶尔在随机页面上失败,上述异常除外。
我已经查看了许多具有类似问题的 StackOverflow 帖子,并尝试了一些建议的修复,例如使用 WebDriverWait 类实现显式等待,使用 try/except 块循环并使用 driver.find_element 重新查找元素... 在发生 StaleElementReferenceException 的条件下方法,并尝试两者
driver.find_element_by_id
和
driver.find_element_by_xpath。
下面是我的代码:
url = "http://www.grownjkids.gov/ParentsFamilies/ProviderSearch"
driver = webdriver.Chrome('MY WEBDRIVER FILE PATH')
driver.implicitly_wait(10)
driver.get(url)
#clears text box
driver.find_element_by_class_name("form-control").clear()
#clicks on search button without putting in any parameters, getting all the results
search_button = driver.find_element_by_id("searchButton")
search_button.click()
#function to find next button
def find(driver):
try:
element = driver.find_element_by_class_name("next")
if element:
return element
except StaleElementReferenceException:
while (attempts < 100):
element = driver.find_element_by_class_name("next")
if element:
return element
attempts += 1
#keeps on clicking next button to fetch each group of 5 results
while True:
try:
nextButton = WebDriverWait(driver, 2000).until(find)
except NoSuchElementException:
break
nextButton.send_keys('\n')
table = driver.find_element_by_id("results")
html_source = table.get_attribute('innerHTML')
print html_source
我有预感将 WebDriverWait 增加到 2000 并且循环 100 次尝试并没有真正起作用(也许它不会进入那个块?)因为无论我增加多少结果都是一样的。对我的代码的任何反馈也很感激,因为这是我第一次使用 Selenium,而且我对 python 也很陌生。
【问题讨论】:
标签: python selenium web-scraping selenium-chromedriver staleelementreferenceexception