如何解决尝试从其他链接中获取信息时,陈旧元素引用元素未附加到页面文档
我在Python上使用Selenium,并尝试移动光标并单击特定元素。这适用于第一个链接,而下一个链接的HTML结构相同,但是当通过相同的webdriver访问第二个链接时,我得到了StaleElementReferenceException。为什么会发生这种情况,我该如何解决?下面是我正在运行的代码。非常感谢!
def getZest(url):
zestlist = []
yearlist = []
driver.get(url)
time.sleep(5)
result = False;
attempts = 0;
while(attempts < 5):
try:
Home_Value = wait.until(EC.presence_of_element_located((By.XPATH,"//a[text()='Home value']")))
action.move_to_element(Home_Value).click().perform()
zestimate = driver.find_element_by_xpath('//*[@id="ds-home-values"]/div/div[3]/button')
action.move_to_element(zestimate).perform()
result = True
break
except exceptions.StaleElementReferenceException as e:
print(e)
attempts = attempts + 1
fivenums = ["https://www.zillow.com/homedetails/212-Haddrell-St-Mount-Pleasant-SC-29464/10922911_zpid/","https://www.zillow.com/homedetails/20-grove-St-Hicksville-NY-11801/31127407_zpid/"]
for num in fivenums:
getZest(num)
解决方法
我能够使用以下代码获得有关第一个和第二个链接的信息,而不会出现任何错误:
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
import selenium.webdriver.support.expected_conditions as EC
from selenium.webdriver.common.by import By
import time
from selenium.common import exceptions
u = 'https://www.oddsportal.com/moving-margins/'
driver = webdriver.Chrome(executable_path=r"chromedriver.exe")
driver.maximize_window()
def getZest(url):
zestlist = []
yearlist = []
driver.get(url)
time.sleep(5)
result = False
attempts = 0
action = webdriver.ActionChains(driver)
wait = WebDriverWait(driver,300)
while(attempts < 5):
try:
Home_Value = wait.until(EC.presence_of_element_located((By.XPATH,"//a[text()='Home value']")))
action.move_to_element(Home_Value).click().perform()
zestimate = driver.find_element_by_xpath('//*[@id="ds-home-values"]/div/div[3]/button')
action.move_to_element(zestimate).perform()
result = True
break
except exceptions.StaleElementReferenceException as e:
print(e)
attempts = attempts + 1
fivenums = ["https://www.zillow.com/homedetails/212-Haddrell-St-Mount-Pleasant-SC-29464/10922911_zpid/","https://www.zillow.com/homedetails/20-Grove-St-Hicksville-NY-11801/31127407_zpid/"]
for num in fivenums:
getZest(num)
在您的代码中,没有显示实例化某些变量的位置,因此,也许这是问题所在。
但是,当打开第一个链接时,该网站向我显示了Google Captcha保护,因此,我想您拥有某种授权,可以在拥有者许可的情况下抓取信息。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。