解決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總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python中判斷語句入門指南(if?elif?else語句)
if elif else語句是Python中的控制語句,用于根據條件執(zhí)行不同的操作,下面這篇文章主要給大家介紹了關于Python中判斷語句入門指南(if?elif?else語句)的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-05-05

