Python異步爬蟲requests和aiohttp中代理IP的使用
爬蟲要想爬的好,IP代理少不了?!,F(xiàn)在網(wǎng)站基本都有些反爬措施,訪問速度稍微快點,就會發(fā)現(xiàn)IP被封,不然就是提交驗證。下面就兩種常用的模塊來講一下代理IP的使用方式。話不多說,直接開始。
requests中代理IP的使用:
requests中使用代理IP只需要添加一個proxies參數(shù)即可。proxies的參數(shù)值是一個字典,key是代理協(xié)議(http/https),value就是ip和端口號,具體格式如下。
try:
response = requests.get('https://httpbin.org/ip', headers=headers,
proxies={'https':'https://221.122.91.74:9401'}, timeout=6)
print('success')
# 檢測代理IP是否使用成功
# 第一種方式,返回發(fā)送請求的IP地址,使用時要在 get() 添加 stream = True
# print(response.raw._connection.sock.getpeername()[0])
# 第二種方式,直接返回測試網(wǎng)站的響應(yīng)數(shù)據(jù)的內(nèi)容
print(response.text)
except Exception as e:
print('error',e)

注意: peoxies的key值(http/https)要和url一致,不然會直接使用本機IP直接訪問。
aiohttp中代理IP的使用:
由于requests模塊不支持異步,迫不得已使用aiohttp,掉了不少坑。
它的使用方式和requests相似,也是在get()方法中添加一個參數(shù),但此時的參數(shù)名為proxy,參數(shù)值是字符串,且字符串中的代理協(xié)議,只支持http,寫成https會報錯。
這里記錄一下我的糾錯歷程。。
首先根據(jù)網(wǎng)上的使用方式,我先試了一下下面的代碼。
async def func():
async with aiohttp.ClientSession() as session:
try:
async with session.get("https://httpbin.org/ip", headers=headers,
proxy='http://183.220.145.3:80', timeout=6) as response:
page_text = await response.text()
print('success')
print(page_text)
except Exception as e:
print(e)
print('error')
if __name__=='__main__':
asyncio.run(func())

修改后,再來
async def func():
con = aiohttp.TCPConnector(verify_ssl=False)
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=False)) as session:
try:
async with session.get("https://httpbin.org/ip", headers=headers,
proxy='http://183.220.145.3:80', timeout=6) as response:
# print(response.raw._connection.sock.getpeername()[0])
page_text = await response.text()
print(page_text)
print('success')
except Exception as e:
print(e)
print('error')

非但沒有解決反倒多了一個警告,好在改一下就好。額~懶得粘了,直接來最終版本吧。。
# 修改事件循環(huán)的策略,不能放在協(xié)程函數(shù)內(nèi)部,這條語句要先執(zhí)行
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
async def func():
# 添加trust_env=True
async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False), trust_env=True) as session:
try:
async with session.get("https://httpbin.org/ip", headers=headers,
proxy='http://183.220.145.3:80', timeout=10) as response:
page_text = await response.text()
print(page_text)
print('success')
except Exception as e:
print(e)
print('error')

雖然糾錯過程有點長,但好在知道怎么用了。
到此這篇關(guān)于Python異步爬蟲requests和aiohttp中代理IP的使用的文章就介紹到這了,更多相關(guān)requests和aiohttp中代理IP內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python列表reverse()函數(shù)使用方法詳解
這篇文章主要詳細介紹了Python列表reverse()函數(shù)使用方法,文章通過代碼示例講解的非常詳細,對我們的學習或工作有一定的幫助,需要的朋友可以參考下2023-07-07
Python使用python-can實現(xiàn)合并BLF文件
python-can庫是 Python 生態(tài)中專注于 CAN 總線通信與數(shù)據(jù)處理的強大工具,本文將使用python-can為 BLF 文件合并提供高效靈活的解決方案,有需要的小伙伴可以了解下2025-07-07

