当遇到反爬虫程序时,以下是一些常见的应对策略及代码示例相关的要点:
python
import requests
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Referer": "https://www.targetwebsite.com/" # 根据实际目标网站填写 Referer
}
response = requests.get("目标网站的 URL", headers=headers)
python
import time
import random
# 在发送请求前随机等待一段时间
time.sleep(random.uniform(1, 5)) # 随机等待 1 到 5 秒之间的时间
python
proxies = {
"http": "http://代理 IP 地址:端口号",
"https": "http://代理 IP 地址:端口号"
}
response = requests.get("目标网站的 URL", proxies=proxies)
python
from selenium import webdriver
# 创建浏览器驱动对象
driver = webdriver.Chrome() # 这里假设使用 Chrome 浏览器驱动,需根据实际安装的浏览器和驱动进行调整
# 访问目标网站
driver.get("目标网站的 URL")
# 等待页面加载完成(根据实际情况调整等待时间)
time.sleep(5)
# 获取页面数据
page_source = driver.page_source
# 关闭浏览器驱动
driver.quit()
python
# 假设使用一个名为 captcha_solver 的第三方验证码识别库
from captcha_solver import solve_captcha
# 获取验证码图片元素(根据实际页面结构定位)
captcha_element = driver.find_element_by_xpath("//img[@id='captcha_img']")
# 获取验证码图片的 URL
captcha_url = captcha_element.get_attribute("src")
# 下载验证码图片
response = requests.get(captcha_url)
with open("captcha.jpg", "wb") as f:
f.write(response.content)
# 使用验证码识别服务识别验证码
captcha_text = solve_captcha("captcha.jpg")
# 填写验证码到输入框(根据实际页面结构定位输入框)
captcha_input = driver.find_element_by_xpath("//input[@id='captcha_input']")
captcha_input.send_keys(captcha_text)