|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这个requests 我怎么携带 header cookies等参数
loop.run_in_executor(None, requests.get, data)
报错代码1:
loop.run_in_executor(None, requests.get, url, headers=headers, cookies=cookies, verify=False, timeout=5)
报错代码2:
kwargs = {'headers': {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}, 'cookies': {'session_id': '12345'}, 'verify': False, 'timeout': 5}
response = await loop.run_in_executor(None, requests.get, url, **kwargs)
这两个都是网上找的答案,都不行,不知道怎么写了。
requests 的 headers 和 cookies 得用关键字参数的形式来传,但是 run_in_executor 没有办法传关键字参数
这时候得配合偏函数解决了,以下是示例代码:
import asyncio
import requests
from functools import partial # 注意这里
async def main():
url = 'http://httpbin.org/get'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
cookies = {'session_id': '12345'}
loop = asyncio.get_running_loop()
get = partial(requests.get, headers=headers, cookies=cookies) # 注意这里
response = await loop.run_in_executor(None, get, url) # 注意这里
print(response.json())
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
|
|