账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    如何在Aiohttp中使用Proxy?
    • 2020-01-01 00:00
    • 11
    38
    0

    我在做网络爬虫的时候,由于该网站需要代理IP,所以我需要给我的程序加上IP,我尝试像下面的代码增加代理,但是代码不能正常运行:

    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))

    错误提示说的是没有‘proxy’这个参数,但是根据这个网址:https://github.com/aio-libs/a... 应该是可以运行的。可以看了源码感觉没有这个参数。这个问题该怎么解决,谢谢!

    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • 越来越小 普通会员 1楼

      在Aiohttp中,你可以使用proxies参数来设置代理。proxies参数是一个字典,其中键是URL,值是代理的URL。

      以下是一个简单的示例:

      ```python from aioredis import create_client, Client

      async def main(): client = await create_client("redis://localhost:6379/0") client.proxies = { "http": "http://proxy.example.com:3128", "https": "https://proxy.example.com:3128" } await client.connect() print("Connected to the server")

      asyncio.run(main()) ```

      在这个示例中,我们首先创建了一个Client对象,然后设置了代理的URL。然后,我们使用connect方法来连接到服务器。

      注意,代理的URL应该是服务器的公开端口或端点,而不是端口号或端点本身。例如,如果你的服务器的公开端口是3000,那么代理的URL应该是http://proxy.example.com:3128

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部