【问题标题】:Why I'm getting different responses when i use urllib.request.urlopen and requests.get为什么我在使用 urllib.request.urlopen 和 requests.get 时得到不同的响应
【发布时间】:2022-01-02 02:21:03
【问题描述】:

为什么我在使用 urllib.request.urlopen 和 requests.get 时得到不同的响应

import requests
r = requests.get('https://upload.wikimedia.org/wikipedia/commons/1/14/Sunset_Boulevard_%281950_poster%29.jpg')
r.status_code

响应 403

from urllib.request import urlopen
r = urlopen('https://upload.wikimedia.org/wikipedia/commons/1/14/Sunset_Boulevard_%281950_poster%29.jpg')
r.getcode()

响应 200

【问题讨论】:

  • 如果您查看 403 响应的内容...您会看到 Error: 403, Forbidden。请遵守用户代理政策 [...]
  • 运行您的 urllib 请求时,我没有收到响应 200 - 我收到 SSL:CERTIFICATE_VERIFY_FAILED
  • 我不知道 User-Agent 发送什么标题 urllibrequests 发送类似 python-requests/2.26 的东西 - 这可以用来阻止脚本。

标签: python python-3.x python-requests urllib


【解决方案1】:

首先您可以查看print( r.content ) 以查看您从服务器获得的信息。
通常你可以得到一些解释,这有助于发现问题。


对于您的代码,它显示标题 User-Agent 存在问题

维基百科:User-Agent policy

一些服务器检查标头User-Agent 为不同的系统/浏览器/设备发送不同的内容。他们还使用它来检测脚本/机器人/垃圾邮件发送者/黑客并阻止它们。

如果我使用来自真实浏览器的标题(或至少短 Mozilla/5.0),那么它可以工作。

import requests

headers = {'User-Agent': 'Mozilla/5.0'}

url = 'https://upload.wikimedia.org/wikipedia/commons/1/14/Sunset_Boulevard_(1950_poster).jpg'
#url = 'https://upload.wikimedia.org/wikipedia/commons/1/14/Sunset_Boulevard_%281950_poster%29.jpg'

r = requests.get(url, headers=headers)

print(r.status_code)
print(r.content[:100])

with open('image.jpg', 'wb') as fh:
    fh.write(r.content)

编辑:

运行代码几次后,即使没有User-Agent,它也开始为我工作。也许他们出于某种不同的原因检查了它。

【讨论】:

  • 非常感谢,但为什么“urllib”不需要标头就可以工作
  • urllib 在标题 User-Agent 中使用不同的值,对于此门户,它可能看起来像正确的标题。 requests 非常受欢迎,也许他们将其标头添加到黑名单中,但他们没有从 urllib 添加标头
  • 运行几次后,即使没有User-Agent,它也开始工作 - 也许有人记得我(或我的 IP)或服务器看到我只运行了几个请求 - 所以即使没有 @,它也开始接受我的请求987654333@
猜你喜欢
  • 1970-01-01
  • 2015-07-09
  • 1970-01-01
  • 2016-11-22
  • 2019-06-28
  • 1970-01-01
  • 2020-06-24
  • 2018-11-22
  • 1970-01-01
相关资源
最近更新 更多