我有一个 python 脚本,列出了一长串网站的标题。这需要很长时间,因此脚本必须运行几个小时。但是,偶尔我会收到错误“无法解码木偶的响应”。
根据我所读到的内容,错误背后的原因似乎并不完全清楚。对我来说,摆脱它并不是首要任务,而是在脚本发生时不要完全停止脚本,这就是当前出现错误时发生的情况。
我该怎么做?
这是代码:
from pyvirtualdisplay import Display
from time import sleep
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.firefox.options import Options
display = Display(visible=0, size(800,600))
display.start()
urlsFile = open ("urls.txt", "r")
urls = urlsFile.readLines()
driver = webdriver.Firefox(executable_path='/usr/local/lib/geckodriver/geckodriver')
driver.set_page_load_timeout(60)
for url in urls:
try:
driver.get(url)
sleep(0.8)
print(driver.title)
except TimeoutException as e:
print("Timeout")
最佳答案
注意:这是我第一次尝试编写Python
<小时/>您只需要构建一种在失败时重试 GET 操作的方法。您仍然希望放弃一定次数的重试,但至少这应该捕获每个 URL 的一次性失败。
def retryable_get(self, url, max_tries = 5)
attempts = 0
while attempts < max_tries
try:
self.get(url)
except Exception:
puts 'An error occured performing a GET to ' + url
finally:
attempts += 1
raise TimeoutException(f'Failed to GET {url} after {max_tries} attempts')
您可以使用以下方式调用它:
retryable_get(driver, url)
如果您想要一种更加面向对象的方法,或者鸭子类型 Firefox 类:
webdriver.Firefox.retryable_get = retryable_get
for url in urls:
try:
driver.retryable_get(url)
sleep(0.8)
print(driver.title)
except TimeoutException as e:
print("Timeout")
关于python - 错误 "Failed to decode response from marionette"后继续 selenium 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56596178/