要編寫一個使用Python的代理IP爬蟲,你可以按照以下步驟進行:
pip install requests
pip install fake_useragent
獲取代理IP列表: 你可以從免費或付費的代理IP提供商處獲取代理IP列表。將獲取到的代理IP列表保存到一個文件中,每個代理IP占一行。
編寫爬蟲代碼: 創建一個Python文件(例如:proxy_spider.py),并編寫以下代碼:
import requests
from fake_useragent import UserAgent
# 讀取代理IP列表
def read_proxy_list(file_path):
with open(file_path, 'r') as file:
proxy_list = [line.strip() for line in file.readlines()]
return proxy_list
# 使用代理IP發送請求
def send_request_with_proxy(url, proxy):
headers = {'User-Agent': UserAgent().random}
try:
response = requests.get(url, headers=headers, proxies={"http": proxy, "https": proxy})
response.raise_for_status()
return response.text
except requests.exceptions.RequestException as e:
print(f"Error with proxy {proxy}: {e}")
return None
# 爬取網頁內容
def crawl(url, proxy_list):
for proxy in proxy_list:
content = send_request_with_proxy(url, proxy)
if content:
print(f"Successfully fetched content from {url} using proxy {proxy}")
# 在這里處理網頁內容,例如保存到文件或解析數據
break
if __name__ == "__main__":
url = "https://example.com" # 要爬取的網頁URL
proxy_file_path = "proxy_list.txt" # 代理IP列表文件路徑
proxy_list = read_proxy_list(proxy_file_path)
crawl(url, proxy_list)
python proxy_spider.py
這個爬蟲將從代理IP列表中隨機選擇一個代理IP,并使用該代理IP發送請求。如果請求成功,它將打印出網頁內容。你可以根據需要修改代碼以處理網頁內容,例如將其保存到文件或解析數據。