【发布时间】:2021-05-10 18:56:39
【问题描述】:
在我的 python selenium 项目中随机发生错误,我使用树莓派从网站上抓取数据。它获取日期、温度、风和降雨量。脚本有时运行正常,但有时会弹出错误:
selenium.common.exceptions.StaleElementReferenceException:消息: 过时的元素引用:元素未附加到页面文档 (会话信息:chrome=84.0.4147.141)
是否有任何包装器可以实现以避免此类错误消息?如果你能分享一个解决方案,我会很高兴。
完整代码:
from selenium import webdriver
import pandas as pd
from datetime import datetime
import time
import schedule
def job():
driver = webdriver.Chrome()
driver.get("https://pent.no/60.19401,11.09936")
date = driver.find_elements_by_class_name("forecast-day-view-date-bar__date")
i = 0
for klikk in date:
date[i].click()
i = i+1
if i==len(date):
break
time = driver.find_elements_by_class_name("forecast-hour-view-hour-label")
count = len(time)-193
temp = driver.find_elements_by_class_name("forecast-hour-view-weather-widget__temperature")
temp2 = temp[::2]
temp3 = temp[1::2]
wind = driver.find_elements_by_class_name("forecast-hour-view-weather-widget__wind-speed")
wind2 = wind[::2]
wind3 = wind[1::2]
rainfall = driver.find_elements_by_class_name("forecast-hour-view-weather-widget__precipitation")
rainfall2 = rainfall[::2]
rainfall3 = rainfall[1::2]
a = []
b = []
c = []
d = []
e = []
f = []
g = []
h = []
k = 0
for datoer in date:
print("Dato:"+datoer.text)
a.append(datoer.text)
if k==0:
a.extend([""]*count)
else:
a.extend([""]*23)
k = k+1
df1 = pd.DataFrame(a, columns= ["Date"])
#
for tider in time:
print("Tid:"+tider.text)
b.append(tider.text)
df2 = pd.DataFrame(b, columns= ["Time"])
#
for tempyr in temp2:
print("Temp yr:"+tempyr.text)
c.append(tempyr.text)
df3 = pd.DataFrame(c, columns= ["Temp Yr"])
for tempstorm in temp3:
print("Temp storm:"+tempstorm.text)
d.append(tempstorm.text)
df4 = pd.DataFrame(d, columns= ["Temp Storm"])
#
for windyr in wind2:
print("Vind yr:"+windyr.text)
e.append(windyr.text)
df5 = pd.DataFrame(e, columns= ["Wind Yr"])
for windstorm in wind3:
print("Vind storm:"+windstorm.text)
f.append(windstorm.text)
df6 = pd.DataFrame(f, columns= ["Wind Storm"])
#
for rainfallyr in rainfall2:
g.append(rainfallyr.text)
if rainfallyr.text == "":
print("Rein yr:"+"0.0 mm")
else:
print("Rein yr:"+rainfallyr.text)
df7 = pd.DataFrame(g, columns= ["Rainfall Yr"])
df7 = df7.replace(r'^\s*$', "0.0 mm", regex=True)
for rainfallstorm in rainfall3:
h.append(rainfallstorm.text)
if rainfallstorm.text == "":
print("Rein storm:"+"0.0 mm")
else:
print("Rein storm:"+rainfallstorm.text)
df8 = pd.DataFrame(h, columns= ["Rainfall Storm"])
df8 = df8.replace(r'^\s*$', "0.0 mm", regex=True)
#
tabell = [df1, df2, df3, df4, df5, df6, df7, df8]
result = pd.concat(tabell, axis=1)
result.to_excel("weather" + str(int(datetime.now().day)) + ".xlsx")
driver.quit()
schedule.every().day.at("00:00").do(job)
while 1:
schedule.run_pending()
time.sleep(60)
编辑:
Traceback (most recent call last):
File "/home/pi/Desktop/Data Scraper/test.py", line 108, in <module>
schedule.run_pending()
File "/home/pi/.local/lib/python3.7/site-packages/schedule/__init__.py", line 563, in run_pending
default_scheduler.run_pending()
File "/home/pi/.local/lib/python3.7/site-packages/schedule/__init__.py", line 94, in run_pending
self._run_job(job)
File "/home/pi/.local/lib/python3.7/site-packages/schedule/__init__.py", line 147, in _run_job
ret = job.run()
File "/home/pi/.local/lib/python3.7/site-packages/schedule/__init__.py", line 466, in run
ret = self.job_func()
File "/home/pi/Desktop/Data Scraper/test.py", line 47, in job
a.append(datoer.text)
File "/usr/local/lib/python3.7/dist-packages/selenium/webdriver/remote/webelement.py", line 76, in text
return self._execute(Command.GET_ELEMENT_TEXT)['value']
File "/usr/local/lib/python3.7/dist-packages/selenium/webdriver/remote/webelement.py", line 633, in _execute
return self._parent.execute(command, params)
File "/usr/local/lib/python3.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python3.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=84.0.4147.141)
【问题讨论】:
-
如果你得到一个陈旧的元素,你必须在离开当前 url 时重新初始化值。如果它是一个标签,只需收集所有的 href 和 driver.get() 给他们。
-
今天我在两个问题中看到了同样的问题。也许您应该在 Stackoverflow 或 Google 上使用
search来为您的问题找到答案。 -
顺便说一句:你应该学会使用简单的
for klikk in date: klikk.click()而不是i = 0、date[i].click()、i = i+1和if i==len(date): break -
总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是屏幕截图)放在有问题的(不是评论)中。还有其他有用的信息。
-
您没有显示完整的错误消息,所以我们不知道哪个元素有问题。并且不要期望我们会运行代码来查看完整的错误消息。也许你只需要
sleep(),这样浏览器就有时间运行所有的JavaScript代码——在你使用click()之前。
标签: python selenium web-scraping error-handling staleelementreferenceexception