[英]Different results between requests.get and aiohttp GET and Httpx module
我正在尝试访问具有机器人预防功能的网站。
通过使用请求的以下脚本,我可以访问该站点。
request = requests.get(url,headers={**HEADERS,'Cookie': cookies})
我得到了所需的 HTML。但是当我使用 aiohttp 时
async def get_data(session: aiohttp.ClientSession,url,cookies):
async with session.get(url,timeout = 5,headers={**HEADERS,'Cookie': cookies}) as response:
text = await response.text()
print(text)
我收到机器人预防页面作为回应。
这是我用于所有请求的标头。
HEADERS = {
'User-Agent': 'PostmanRuntime/7.29.0',
'Host': 'www.dnb.com',
'Connection': 'keep-alive',
'Accept': '/',
'Accept-Encoding': 'gzip, deflate, br'
}
我比较了 requests.get 和 aiohttp 的请求标头,它们是相同的。
结果有什么不同的原因吗? 如果是,为什么?
编辑:我检查了 httpx 模块,问题也出现在httpx.Client()
和httpx.AsyncClient()
上。
response = httpx.request('GET',url,headers={**HEADERS,'Cookie':cookies})
也不起作用。 (不是异步的)
我尝试使用 wireshark 捕获数据包以比较请求和 aiohttp。
服务器:
import http
server = http.server.HTTPServer(("localhost", 8080),
http.server.SimpleHTTPRequestHandler)
server.serve_forever()
有要求:
import requests
url = 'http://localhost:8080'
HEADERS = {'Content-Type': 'application/json'}
cookies = ''
request = requests.get(url,headers={**HEADERS,'Cookie': cookies})
请求数据包:
GET / HTTP/1.1
Host: localhost:8080
User-Agent: python-requests/2.27.1
Accept-Encoding: gzip, deflate, br
Accept: */*
Connection: keep-alive
Content-Type: application/json
Cookie:
使用 aiohttp:
import aiohttp
import asyncio
url = 'http://localhost:8080'
HEADERS = {'Content-Type': 'application/json'}
cookies = ''
async def get_data(session: aiohttp.ClientSession,url,cookies):
async with session.get(url,timeout = 5,headers={**HEADERS,'Cookie': cookies}) as response:
text = await response.text()
print(text)
async def main():
async with aiohttp.ClientSession() as session:
await get_data(session,url,cookies)
asyncio.run(main())
aiohttp数据包:
GET / HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cookie:
Accept: */*
Accept-Encoding: gzip, deflate
User-Agent: Python/3.10 aiohttp/3.8.1
如果该站点似乎接受来自请求的数据包,那么您可以尝试通过设置标头来使 aiohttp 数据包相同:
HEADERS = { 'User-Agent': 'python-requests/2.27.1','Accept-Encoding': 'gzip, deflate, br', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'application/json','Cookie': ''}
如果您还没有,我建议使用 wireshark 捕获请求以确保 aiohttp 不会弄乱您的标头。
您也可以尝试其他用户代理字符串,或尝试不同顺序的标头。 该顺序不重要,但某些站点无论如何都会检查它以保护机器人(例如在这个问题中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.