python - 将 Aiohttp 与代理一起使用
问题描述
我正在尝试使用 async 从 url 列表(由 id 标识)中获取 HTML。我需要使用代理。
我正在尝试将 aiohttp 与如下代理一起使用:
import asyncio
import aiohttp
from bs4 import BeautifulSoup
ids = ['1', '2', '3']
async def fetch(session, id):
print('Starting {}'.format(id))
url = f'https://www.testing.com/{id}'
async with session.get(url) as response:
return BeautifulSoup(await response.content, 'html.parser')
async def main(id):
proxydict = {"http": 'xx.xx.x.xx:xxxx', "https": 'xx.xx.xxx.xx:xxxx'}
async with aiohttp.ClientSession(proxy=proxydict) as session:
soup = await fetch(session, id)
if 'No record found' in soup.title.text:
print(id, 'na')
loop = asyncio.get_event_loop()
future = [asyncio.ensure_future(main(id)) for id in ids]
loop.run_until_complete(asyncio.wait(future))
根据这里的一个问题:https ://github.com/aio-libs/aiohttp/pull/2582似乎ClientSession(proxy=proxydict)
应该可以工作。
但是,我收到一个错误"__init__() got an unexpected keyword argument 'proxy'"
知道我应该怎么做才能解决这个问题吗?谢谢你。
解决方案
您可以在 session.get 调用中设置代理配置:
async with session.get(url, proxy=your_proxy_url) as response:
return BeautifulSoup(await response.content, 'html.parser')
如果您的代理需要身份验证,您可以在代理的 url 中设置它,如下所示:
proxy = 'http://your_user:your_password@your_proxy_url:your_proxy_port'
async with session.get(url, proxy=proxy) as response:
return BeautifulSoup(await response.content, 'html.parser')
或者:
proxy = 'http://your_proxy_url:your_proxy_port'
proxy_auth = aiohttp.BasicAuth('your_user', 'your_password')
async with session.get(url, proxy=proxy, proxy_auth=proxy_auth) as response:
return BeautifulSoup(await response.content, 'html.parser')
更多详情请看这里
推荐阅读
- json - 将 JSON 文件的嵌套子级导入 Postgresql
- amazon-web-services - 我们如何将 JSON 文件中处理的 JSON 消息的基本详细信息记录到用于创建基于日志的指标的 cloudwatch 日志流中?
- python - 如何在 Python 中使用逗号分隔变量的列表字符串来函数参数?
- php - 异常消息:未定义的变量:
- sharepoint - 获取授予“Everyone”组权限的所有位置(列表/库/项目)
- javascript - 如何使jszip生成相同的缓冲区
- java - 在 Java 中将 String 作为方法参数传递时创建的 String 对象的数量
- java - @NotNull 不会一直使用 MethodValidationPostProcessor 运行
- python-3.x - 我想将 tt[ ] 的每 6 个元素分配给星期一到星期五,最后 4 个元素分配给星期六
- python - 如何比较字典中的值