Selenium Chromedriver:防止 span 元素出现陈旧元素异常

问题描述 投票:0回答:1

我目前正在尝试自动从网站收集数据。网站本身在加载数据时不会暂停,因此我让程序在输入搜索查询后跟踪返回的搜索结果的显示数量,以尝试确保在网站完成加载之前我不会收集数据它的数据库。检查该数字所在的文本部分有时会给我一个陈旧的参考错误。

while TimingLoops < 5:
        TimingLoops = TimingLoops+1
        time.sleep(0.05)
        newelement = driver.find_element(By.XPATH, "/html/body/div[3]/div[3]/div[2]/div[1]/div[2]/span[1]")
        newelementText = newelement.text

Exception has occurred: StaleElementReferenceException Message: stale element reference: stale element not found in the current frame

为了防止过时的引用错误,我插入了一行代码来检查是否存在我想要的文本。我假设可能发生的情况是跨度中的值在更改过程中消失了?我预计这行代码会阻止我的代码继续前进,直到元素出现并可供使用。我是否使用了错误的预期条件来执行此操作?我对 HTML 和 python 的了解都非常有限,所以也许这只是用于此元素类型的错误检查类型?我尝试使用 staleness_of 检查,但不能在元组上使用,并且搜索硒预期条件列表并没有发现任何比我现在使用的条件更适合的内容。

 while TimingLoops < 5:
        TimingLoops = TimingLoops+1
        time.sleep(0.05)
        newelement = WebDriverWait(driver,120).until(
        EC.presence_of_element_located((By.XPATH, 
 "/html/body/div[3]/div[3]/div[2]/div[1]/div[2]/span[1]"))
        )
        newelementText = newelement.text

我仍然收到错误

Exception has occurred: StaleElementReferenceException Message: stale element reference: stale element not found in the current frame

我是否必须恢复使用某种显式等待?

这是网站:https://bonap.net/TDC/# 这就是我想要捕捉的特定元素

selenium-webdriver selenium-chromedriver staleelementreferenceexception
1个回答
0
投票

我没有遇到你所遇到的问题。这是我编写的代码并且它正在运行。我运行了五次,没有任何问题或错误。

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

url = 'https://bonap.net/TDC/#'
driver = webdriver.Chrome()
driver.maximize_window()
driver.get(url)

wait = WebDriverWait(driver, 10)
counts = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "#genus-panel div.taxon-panel-description > span")))
print(f'genera: {counts[0].text}')
print(f'species: {counts[1].text}')

然后打印出来

genera: 3625
species: 24184
© www.soinside.com 2019 - 2024. All rights reserved.