解决python异步框架aiohttp无法使用本地代理问题
更新时间:2024年07月18日 09:06:54 作者:FOAF-lambda
这篇文章主要介绍了解决python异步框架aiohttp无法使用本地代理问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
问题
- 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总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Django原生sql也能使用Paginator分页的示例代码
这篇文章主要介绍了Django原生sql也能使用Paginator分页的示例代码,主要使用了count和__getslice__,有兴趣的可以了解一下2017-11-11
python3 BeautifulSoup模块使用字典的方法抓取a标签内的数据示例
这篇文章主要介绍了python3 BeautifulSoup模块使用字典的方法抓取a标签内的数据,结合实例形式Fenix了python3 BeautifulSoup模块进行数据的抓取相关操作技巧,需要的朋友可以参考下2019-11-11
jupyter notebook保存文件默认路径更改方法汇总(亲测可以)
安装Anaconda后,新建文件的默认存储路径一般在C系统盘,那么路径是什么呢?如何更改jupyter notebook保存文件默认路径呢?今天小编就这一问题通过两种方法给大家讲解,需要的朋友跟随小编一起看看吧2021-06-06


最新评论