【问题标题】:Using Aiohttp with Proxy将 Aiohttp 与代理一起使用
【发布时间】:2018-08-17 02:54:58
【问题描述】:

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

知道我应该怎么做来解决这个问题吗? 谢谢。

【问题讨论】:

    标签: python asynchronous python-asyncio aiohttp


    【解决方案1】:

    您可以在 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

    【讨论】:

    • 如果您想连接到.onion 站点,您可以找到答案here
    【解决方案2】:

    我真傻 - 在阅读了 @Milan Velebit 的文档后,我意识到变量应该是 trust_env=True 而不是 proxyproxies。代理信息应该来自/设置在 HTTP_PROXY / HTTPS_PROXY 环境变量。

    【讨论】:

      【解决方案3】:

      根据他们的documentation,确实没有 proxy 参数,而是使用 proxies

      【讨论】:

      • 不幸的是同样的问题:TypeError: __init__() got an unexpected keyword argument 'proxies'
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      • 2018-11-02
      • 2014-03-06
      • 2016-12-09
      • 2013-06-11
      • 2012-06-08
      相关资源
      最近更新 更多