在使用Python進行XPath爬蟲時,為了避免IP被封,可以采取以下幾種策略:
import requests
from lxml import etree
proxies = {
'http': 'http://代理IP:端口',
'https': 'https://代理IP:端口',
}
url = '目標網址'
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, proxies=proxies)
html = response.text
tree = etree.HTML(html)
# 提取數據
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
time.sleep()
函數:import time
time.sleep(5) # 等待5秒
cookies = {
'cookie_name': 'cookie_value',
'another_cookie_name': 'another_cookie_value',
}
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, cookies=cookies)
請注意,爬蟲行為應遵守網站的robots.txt規則和相關法律法規。在進行爬蟲開發時,請確保自己的行為合法合規。