当前位置: 代码网 > it编程>前端脚本>Python > 解决python异步框架aiohttp无法使用本地代理问题

解决python异步框架aiohttp无法使用本地代理问题

2024年07月18日 Python 我要评论
问题aiohttp 在全局代理模式下无法访问墙外的网址,而requests可以aiohttp不支持https代理,无论访问的网址是http还是https,使用代理是字符串proxy='http

问题

  • aiohttp 在全局代理模式下无法访问墙外的网址,而requests可以
  • aiohttp不支持https代理,无论访问的网址是http还是https,使用代理是字符串proxy='http://127.0.0.1:10080'
import aiohttp
import asyncio
headers = {
        'user-agent': "mozilla/5.0 (windows nt 6.1; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/69.0.3494.0 safari/537.36",
}
async def fetch(session,url):
    async with session.get(url=url,headers=headers,timeout=50,verify_ssl=false,proxy='http://127.0.0.1:10080') as resposne:
        print(resposne.status)
        return await resposne.text()
async def main():
    async with aiohttp.clientsession() as session:
        url='https://www.google.com'
        html = await fetch(session,url)
        print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main()) 
  • 当session.get里面不传入proxy时
  • 会根据clientsession里面的一个参数叫trust_env是否为true来使用本地代理
  • 但源码中的使用条件是
elif self._trust_env:
    for scheme, proxy_info in proxies_from_env().items():
        if scheme == url.scheme:
            proxy = proxy_info.proxy
            proxy_auth = proxy_info.proxy_auth
            break
  • scheme == url.scheme 这个条件阻挡了请求https网址
  • aiohttp不支持https代理
  • 所以这是一个矛盾的地方

解决方式1

  • 修改源码
  • 对scheme == url.scheme这个条件进行修改
  • 并且在aiohttp.clientsession(trust_env=true)传入trust_env=true
  • 这种方式不提倡

解决方式2

  • 获取本地代理
  • 然后在没有代理时在session.get使用本地代理
def get_local_proxy():
    
    from urllib.request import getproxies
    proxy = getproxies()['http']
    #proxies = {'http': 'http://127.0.0.1:10809', 'https': 'http://127.0.0.1:10809'}
    proxies = {'http': proxy , 'https': proxy}
    return proxies

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持3w代码。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com