Python3打开图片时请求ConnectionResetError(10054)

问题描述 投票:0回答:5

我试图从“http://xxx.jpg”等网站下载图片。

代码:

headers={'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'}
url='http://xxx.jpg'
response = requests.get(url,headers=headers)
downloadFunction()

错误写道:

requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

第一次请求时发生错误,因此不是请求频率导致错误。而且我仍然可以使用浏览器打开网站,因此我只需要代码使其更像浏览器。除了设置用户代理之外,我怎样才能实现这一点?

python python-requests web-crawler
5个回答
14
投票

我知道这不是你的情况,而且这确实很旧,但是在搜索谷歌时我偶然发现了这一点,所以我将在这里留下解决我的问题的方法:

test_link = "https://www.bbb.org/washington-dc-eastern-pa/business-reviews/online-education/k12-inc-in-herndon-va-190911943/#sealclick"
page = requests.get(test_link)

我收到错误:

requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

所以这不是多个连接,我认为问题在于标头,一旦我放置标头,错误就消失了,这是之后的代码:

test_link = "https://www.bbb.org/washington-dc-eastern-pa/business-reviews/online-education/k12-inc-in-herndon-va-190911943/#sealclick"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0",
    "Accept-Encoding": "*",
    "Connection": "keep-alive"
}
page = requests.get(test_link, headers=headers)

1
投票

当服务器通过 https 托管在我的计算机上并且 SSL 证书未正确安装时,我遇到了此错误。

按照正确安装服务器证书的说明解决了问题:

https://coderead.wordpress.com/2014/08/07/enabling-ssl-for-self-hosted-nancy/ https://www.cloudinsidr.com/content/how-to-install-the-most-recent-version-of-openssl-on-windows-10-in-64-bit/


1
投票

对我来说,我必须添加带有

Content-Type
accept
的标头(因为 API 需要这两个字段)并且一切正常:)。

    headers = {
        'Content-Type': 'application/json',
        'accept': 'application/json',
    }

    result = requests.post(environ.get('customer_api_url'),
                           headers = headers,
                           json=lead)

0
投票

在我的例子中,雇主的防火墙阻止了 post 和 put 请求,但没有阻止 Get 请求。因此,如果您要连接以查看 API 的外部连接是否有效,则值得尝试断开与 VPN 的连接并通过热点/开放网络进行连接。 稍后,如果与工作相关,您可以请求您的雇主将网站 Api 列入白名单。

记录下来,因为它可以帮助那些面临类似网络相关问题的人。


0
投票

我在 Python 3.12.2 和请求 2.31.0 中遇到了这个问题。

我尝试从本地 API 向第三方 API 发出请求,但第三方 API 始终返回相同的错误。但是,当我使用 Postman 或 Insomnia 时,对第三方端点的请求没有问题。

问题是我从 PC 上的本地 Google Drive 文件夹运行 API。当我将其移出那里后,本地 API 就开始工作了。这个问题对我来说是新问题,因为在另一台具有类似设置和相同 API 的 PC 上,我没有遇到这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.