使用requests包設置代理

一、什麼是代理?

代理(Proxy)是計算機網路中的一種應用服務,為了避免直接連接到目標伺服器引發的一系列安全問題,通過代理伺服器來進行請求和響應。代理伺服器可以隱藏客戶端真實IP地址,加密通信,減少訪問延遲等。

在使用requests包發送HTTP請求時,使用代理可以實現一些特殊的功能,如訪問被限制的網站,獲取不同地區的搜索結果等。

二、requests包中設置代理

requests包中設置代理的方式非常簡單,只需要在請求發送前設置proxies參數即可。具體的用法如下:

import requests

proxies = {
    "http": "http://user:password@ip:port",
    "https": "http://user:password@ip:port"
}

response = requests.get(url, proxies=proxies)

其中,proxies為一個字典,代表http和https協議的代理,ip和port分別為代理伺服器的ip地址和埠號,如果需要驗證代理,user和password為代理伺服器的用戶名和密碼。需要注意的是,這裡使用http協議來連接代理伺服器,並不是使用https。

另外,如果代理伺服器不需要驗證,可以簡單地寫成:

proxies = {
    "http": "http://ip:port",
    "https": "http://ip:port"
}

三、使用HTTP代理

如果代理伺服器只支持HTTP協議,可以如下設置:

proxies = {
    "http": "http://ip:port",
}

這種情況下,如果要訪問HTTPS網站,需要使用繞過驗證的方式:

proxies = {
    "http": "http://ip:port",
    "https": "https://ip:port",
}

response = requests.get(url, proxies=proxies, verify=False)

其中,verify=False繞過SSL證書驗證。

四、使用SOCKS代理

如果代理伺服器支持SOCKS協議,可以使用SocksiPy庫來實現代理,先用pip安裝SocksiPy:

pip install SocksiPy

然後使用如下方式設置代理:

import socks
import socket
import requests

# Set the socks proxy server
socks.set_default_proxy(socks.SOCKS5, "ip", port)

# Route the HTTP traffic through the SOCKS proxy server
socket.socket = socks.socksocket

response = requests.get(url)

五、如何使用特定的代理?

當我們需要在請求中使用不同的代理時,可以預先設置多個代理,並在請求時選擇相應的代理。如下所示:

import requests

proxies_1 = {
    "http": "http://ip_1:port",
    "https": "http://ip_1:port"
}
proxies_2 = {
    "http": "http://ip_2:port",
    "https": "http://ip_2:port"
}

response = requests.get(url, proxies=proxies_1)
response = requests.get(url, proxies=proxies_2)

六、requests_cache緩存代理

使用requests_cache庫可以在本地緩存HTTP響應,在網路不暢或者伺服器響應緩慢時提高效率。如果我們在本地搭建了一個http緩存代理,可以將代理地址設置為requests_cache的backend參數,如下所示:

import requests_cache
import requests

requests_cache.install_cache('cache_proxy', backend='http', expire_after=None)

response = requests.get(url)

七、總結

requests包使設置代理非常簡單,只需要在請求發送前設置proxies參數即可。我們可以通過http代理伺服器和socks代理伺服器訪問互聯網,並且可以設置多個代理,實現訪問不同地區的搜索結果。另外,使用requests_cache庫可以在本地緩存HTTP響應,提高客戶端效率。

原創文章,作者:IXWWX,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/369046.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
IXWWX的頭像IXWWX
上一篇 2025-04-12 13:00
下一篇 2025-04-12 13:00

相關推薦

發表回復

登錄後才能評論