我正在用python 3开发一个简单的web scraper,但当我发送get或post请求时,响应是403.在python中,2可以很好地工作.我在两个版本中使用了相同版本的请求库.我有

请求数=2.22.0

certifi=2019.9.11

from requests import get
url = 'https://www.gamestop.com/'
header = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-US,en;q=0.5',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0',
    'DNT': '1',
    'Upgrade-Insecure-Requests': '1',
    'Connection': 'keep-alive',
    'Host': 'www.gamestop.com'
}
res = get(url, headers=header, verify=False).status_code
print(res)
# 403 when using python 3.7.4
# 200 when using python 2.7.16

Edit by @blhsing:

下面的列表根据注释记录了哪些特定的Python版本有效,哪些版本失败.到目前为止,跨平台的每个特定Python版本的成功和失败都是一致的.

请使用您自己的结果以及用于生成结果的特定Python版本,随意编辑问题的这一部分.

2.7.14 works (blhsing)
2.7.16 works (repl.it)
3.6.5 works (blhsing)
3.6.8 fails (Reinderien and blhsing)
3.7.3 works (wim and blhsing)
3.7.4 fails (repl.it and blhsing)
3.8.0 fails (OP)

repl上的演示.它:Python 2.7.16Python 3.7.4

推荐答案

这是urlib3引发的异常:

/本垒/亚军/.local/share/virtualenvs/python3/lib/python3.7/站点包/urllib3/connectionpool.py:https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings4:

根据latest release notes, section 1.25.5 (2019-09-19)人的说法:

增加BPO-37428 affecting Python <3.7.4 and OpenSSL的缓解措施

你可以跟着issue on Github号,它已经关闭了.

TLDR

User @sethmlarson on Githuburllib3上发现了这个错误:

创建_urlib3_context():

    # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is
    # necessary for conditional client cert authentication with TLS 1.3.
    # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older
    # versions of Python.
    if getattr(context, "post_handshake_auth", None) is not None:
        context.post_handshake_auth = True

将此值设置为True将启用服务器证书验证,而不是禁用.

Python-3.x相关问答推荐

我没有';无法理解此TemplateDoesNotExist错误

CSV-DAT 转换时将引号添加到数据中

命名空间前缀无效

如何立即从asyncio.Task获取异常?

如何将 WebDriver 传输到导入的测试?

Pandas 在每组两个条件之间获得时间增量

python2和python3中的列表生成器

如何在Pandas 中按条件计算分组?

Tkinter IntVar 返回 PY_VAR0 而不是值

如何使用pandas python获取数据框中每列的最大长度

Python:如何判断一个项目是否被添加到一个集合中,没有 2x(hash,lookup)

为什么包含类的名称不被识别为返回值函数注释?

为什么等效的 Python 代码要慢得多

用 numpy nan 查找列表的最大值

plt.cm.get_cmap 中可以使用哪些名称?

警告:请使用 tensorflow/models 中的官方/mnist/dataset.py 等替代方案

具有不均匀间隙的 Python 范围

在 macbook pro M1 上安装 Tensorflow 时出现zsh:非法硬件指令 python

如何使用 python http.server 运行 CGI hello world

如何从Pandas 中的字符串中提取前8个字符