在Python中,要實現IP輪換,可以使用代理服務器。以下是一個使用requests
庫和免費代理服務器的示例:
requests
庫(如果尚未安裝):pip install requests
httpbin.org
提供的免費代理。創建一個名為ip_rotation.py
的Python文件,并添加以下代碼:import requests
def get_proxy():
response = requests.get("https://httpbin.org/ip")
proxy = response.json()["origin"]
return proxy
def crawl(url):
proxy = get_proxy()
print(f"Using proxy: {proxy}")
try:
response = requests.get(url, proxies={"http": proxy, "https": proxy})
response.raise_for_status()
print(response.text)
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
if __name__ == "__main__":
url = "https://www.example.com" # Replace with the URL you want to crawl
crawl(url)
在這個示例中,我們首先定義了一個get_proxy
函數,該函數通過訪問httpbin.org/ip
來獲取一個免費的代理服務器地址。然后,我們定義了一個crawl
函數,該函數使用獲取到的代理服務器地址發送HTTP請求。
請注意,免費代理服務器的可用性和速度可能會受到限制。在生產環境中,建議使用付費的代理服務以獲得更穩定和高速的代理。此外,還可以考慮使用代理池來管理多個代理服務器,以便在需要時輪換IP地址。