【问题标题】:Selenium Connection RefusedSelenium 连接被拒绝
【发布时间】: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


    【解决方案1】:

    我的代码仍然偶尔会遇到问题(可以通过使用代理解决),但我想我找到了问题的根源。此循环预计第一个模式匹配将返回.edu.com,但预计不会返回.org。因此,当第一个搜索结果返回.org 时,我的代码将无限期运行。这是问题的根源:

    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)') # does not anticipate .org's 
    

    现在我的代码运行正常,但当代码运行时间过长时我确实会遇到错误(在这种情况下,问题的根源要清楚得多)。

    【讨论】:

      【解决方案2】:

      您过早退出 Chrome 驱动程序。在您调用chrome.quit() 之后,它将导致对chrome.get('https://google.com') 的后续调用失败,然后自动重试导致 MaxRetryError。

      尝试删除对chrome.quit()的调用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-18
        • 2017-10-03
        • 2018-04-21
        • 2018-04-23
        • 2017-08-08
        • 2018-07-25
        • 2018-11-07
        • 2021-04-10
        相关资源
        最近更新 更多