【问题标题】:The code gives Connection Error error after a while代码在一段时间后给出连接错误错误
【发布时间】:2020-01-19 03:49:32
【问题描述】:

捕获数据时出现“连接错误”错误。它工作了一段时间然后出现错误,我该如何克服这个错误。

import requests
from bs4 import BeautifulSoup

url = "https://www.example.com"
for page in range(0,951,50):
    new_url = url +page + "&pagingSize=50" 
    r = requests.get(new_url)            
    source = BeautifulSoup(r.content,"html.parser")               
    content = source.select('tr.searchResultsItem:not(.nativeAd, .classicNativeAd)')
    print(content)

当我收到此错误时,我希望它等待一段时间并从中断处继续

错误:

ConnectionError: ('Connection aborted.', OSError("(10054, 'WSAECONNRESET')"))

【问题讨论】:

  • 请分享整个错误信息。你有minimal reproducible example吗?
  • 您可能受到您要连接的服务的限制。如果没有示例且没有完整的错误消息,很难判断
  • 我在问题中添加了错误

标签: python beautifulsoup python-requests


【解决方案1】:

您可以通过实施重试来解决连接重置(和其他网络问题)。基本上,您可以告诉请求在出现问题时自动重试。

你可以这样做:

import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

session = requests.Session()

# in case of error, retry at most 3 times, waiting
# at least half a second between each retry
retry = Retry(total=3, backoff_factor=0.5)  

adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)

然后,而不是:

r = requests.get(new_url)

你可以使用:

r = session.get(new_url)

另请参阅Retry 的文档,了解它支持的场景的完整概述。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 2018-09-04
    相关资源
    最近更新 更多