要配置一個使用Python的代理IP爬蟲,你需要遵循以下步驟:
requests
和fake_useragent
庫。如果沒有,可以使用以下命令安裝: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 main():
url = "https://example.com" # 替換為你想要爬取的網站URL
proxy_list_file = "proxy_list.txt" # 代理IP列表文件路徑
proxy_list = read_proxy_list(proxy_list_file)
for proxy in proxy_list:
content = send_request_with_proxy(url, proxy)
if content:
print(f"Content with proxy {proxy}:")
print(content)
if __name__ == "__main__":
main()
python proxy_spider.py
這個爬蟲將使用代理IP列表中的每個代理IP發送請求到指定的URL,并打印響應內容。你可以根據需要修改代碼以滿足你的需求。