在Python中,您可以使用requests
庫和requests_proxy_auth
庫來設置代理。首先,確保您已經安裝了這兩個庫。如果沒有,請使用以下命令安裝:
pip install requests requests_proxy_auth
接下來,您可以使用以下代碼設置代理:
import requests
from requests_proxy_auth import ProxyAuth
url = 'https://example.com'
proxy = 'http://username:password@proxyserver:port'
proxies = {
'http': proxy,
'https': proxy,
}
# 如果代理需要身份驗證,可以使用以下方式設置
auth = ProxyAuth(username='username', password='password')
proxies = {
'http': proxy,
'https': proxy,
}
response = requests.get(url, proxies=proxies, auth=auth)
print(response.text)
在這個例子中,我們首先導入requests
庫和ProxyAuth
類。然后,我們定義要訪問的URL和代理服務器的信息。接著,我們創建一個名為proxies
的字典,其中包含HTTP和HTTPS代理設置。最后,我們使用requests.get()
方法發送GET請求,并將proxies
和auth
參數傳遞給它。這將使用指定的代理服務器發送請求。