我正试图访问一个站点与机器人的预防。
使用以下使用请求的脚本,我可以访问站点。
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})也不起作用。(不是异步的)
发布于 2022-04-18 22:04:58
我尝试用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不会干扰您的标题。
您也可以尝试其他用户代理字符串,也可以按不同的顺序尝试头。订单并不重要,但是一些站点无论如何都会检查它以保护机器人(例如,在this question中)。
https://stackoverflow.com/questions/71914299
复制相似问题