默认情况下,Requests 在发出请求时会发送唯一的用户代理。
>>> r = requests.get('https://google.com')
>>> r.request.headers
{'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
您正在使用的网站可能试图通过拒绝用户代理的任何请求来避免抓取工具python-requests
.
要解决这个问题,您可以更改您的用户代理 https://stackoverflow.com/questions/10606133/sending-user-agent-using-requests-library-in-python发送请求时。由于它可以在您的浏览器上运行,因此只需复制您的浏览器用户代理(您可以通过 Google 搜索,或记录对网页的请求并复制您的用户代理)。对我来说,它是Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36
(真是拗口),所以我像这样设置我的用户代理:
>>> headers = {
... 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'
... }
然后发送带有新标头的请求(新标头将添加到默认标头中,除非它们具有相同的名称,否则它们不会替换它们):
>>> r = requests.get('https://google.com', headers=headers) # Using the custom headers we defined above
>>> r.request.headers
{'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
现在我们可以看到请求是使用我们首选的标头发送的,希望网站无法区分请求和浏览器之间的区别。