【发布时间】:2019-10-18 21:49:46
【问题描述】:
我正在使用 Python/Selenium 抓取 Google 搜索页面,从昨晚开始,我遇到了 MaxRetyError: p[Errno 61] Connection refused 错误。我调试了我的代码,发现错误从这里的代码块开始”
domain = pattern.search(website)
counter = 2
# keep running this until the url appears like normal
while domain is None:
counter += 1
# close chrome and try again
print('link not found, closing chrome and restarting ...\nwaiting {} seconds...'.format(counter))
chrome.quit()
time.sleep(counter)
# chrome = webdriver.Chrome()
time.sleep(10) ### tried inserting a timer.sleep to delay request
chrome.get('https://google.com') ### error is right here. This is the second instance of chrome.get in this script
target = chrome.find_element_by_name('q')
target.send_keys(college)
target.send_keys(Keys.RETURN)
# parse the webpage
soup = BeautifulSoup(chrome.page_source, 'html.parser')
website = soup.find('cite', attrs={'class': 'iUh30'}).text
print('tried to get URL, is this it? : {}\n'.format(website))
pattern = re.compile(r'\w+\.(edu|com)')
domain = pattern.search(website)
我不断收到以下错误:
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='ADDRESS', port=PORT): Max retries exceeded with url: /session/92ca3da95353ca5972fb5c520b704be4/url (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x11100e4e0>: Failed to establish a new connection: [Errno 61] Connection refused',))
正如您在上面的代码块中看到的,我输入了timer.sleep(),但它似乎根本没有帮助。对于上下文,此脚本是函数的一部分,在另一个脚本中循环重复调用该函数。但同样,我确保在每次调用 webdriver.get() 方法之间添加延迟。截至目前,我的脚本在此循环的第一次迭代中失败。
我尝试用谷歌搜索这个问题,但我找到的最接近的是this。它似乎说明了相同的确切错误,并且最佳答案确定了导致问题的相同方法,但我并不真正理解解决方案和结论部分在说什么。我知道MaxRetryError 令人困惑,但解决方案究竟是什么?
它提到了 max_retries 参数和 Tracebacks,但我不知道它们在这种情况下的含义。有什么方法可以捕捉到这个错误(在硒的情况下)?我在 Stack Exchange 上有一些线程提到了捕获错误,但仅在 urllib3 的上下文中。就我而言,我需要为 Selenium 包捕获相同的错误。
感谢您的建议
【问题讨论】:
标签: python-3.x selenium selenium-chromedriver try-catch