要使用Python代理IP爬蟲,你需要首先安裝一些庫,如requests, bs4 和 fake_useragent。你可以使用以下命令安裝這些庫:
pip install requests
pip install beautifulsoup4
pip install fake_useragent
接下來,你可以使用以下代碼創建一個簡單的代理IP爬蟲:
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
# 代理IP池
proxies = [
{'http': 'http://1.2.3.4:8080'},
{'http': 'http://5.6.7.8:8080'},
# 更多代理IP...
]
# 隨機User-Agent
ua = UserAgent()
def get_proxy():
return random.choice(proxies)
def fetch_url(url):
proxy = get_proxy()
headers = {'User-Agent': ua.random}
try:
response = requests.get(url, headers=headers, proxies=proxy, timeout=5)
response.raise_for_status()
return response.text
except requests.exceptions.RequestException as e:
print(f"Error fetching {url}: {e}")
return None
def parse_html(html):
soup = BeautifulSoup(html, 'html.parser')
# 根據網頁結構解析數據,例如:
titles = soup.find_all('h2', class_='title')
for title in titles:
print(title.get_text())
if __name__ == "__main__":
url = "https://example.com" # 要爬取的網址
html = fetch_url(url)
if html:
parse_html(html)
這個示例代碼首先定義了一個代理IP池,然后使用fake_useragent庫隨機選擇一個User-Agent。fetch_url函數接受一個URL,使用代理IP和隨機User-Agent發起請求,并返回響應內容。parse_html函數解析HTML內容并根據網頁結構提取所需數據。
請注意,這個示例僅用于演示目的,實際應用中可能需要根據目標網站的結構和反爬蟲策略進行調整。同時,使用代理IP爬蟲時,請確保遵守相關法律法規和網站的使用條款。