python - 将 Aiohttp 与代理一起使用

标签 python asynchronous python-asyncio aiohttp

我正在尝试使用异步从 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')

有关更多详细信息,请参阅 here

关于python - 将 Aiohttp 与代理一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51887784/

相关文章:

python - 表示文本中后续更改并使用 Python 使用此表示的标准方法是什么?

c# - 使用 Task.ContinueWith 时如何避免嵌套的 AggregateException?

python - 如何替换关闭的事件循环?

python - 谷歌距离矩阵 API : How to specify origin-destination pairs?

python - 为什么当我将 GridSearchCV 与 roc_auc 评分一起使用时,grid_search.score(X,y) 和 roc_auc_score(y, y_predict) 的分数不同?

python - ZeroMQ ROUTER 套接字无法向 REP 套接字发送消息

c# - 如果我在未定义为任务的 IQueryable 上使用 await + ToListAsync() 是否正确

javascript - Promise.all() 等待对象属性的返回

python - 如何在 python 3.4 中调用方法并使其在后台运行?

Python asyncio : Queue. join() 仅在未引发异常时完成,为什么? (上下文:编写异步映射函数)