python 解决验证码反爬(一)
导语
大家在使用python 爬取数据时,都会经常遇到网站的一些反扒措施。例如:js加密、验证码、IP封锁等等。而今天更大家分享的就是关于验证码的反反爬,验证码是我们最为常见的一种反爬手段,为了验证是人进行访问还是机器进行访问。所以我们需要去通过模拟人的操作,让服务器误以为是人为的进行访问,从而达到反反爬的目的。
思路
我们以易盾 http://dun.163.com/trial/picture-click 的点触验证码为例。我们使用 selenuim
这个库去自动化驱动浏览器访问,然后获取到验证码图片,将图片发给打码平台(以 超级鹰 为例),通过打码平台返回的点触坐标,通过模拟人为的轨迹(移动、点触)从而实现反反爬。
开发工具
Python版本:3.5
相关模块:
- Pillow 模块
- selenium 模块
- 以及Python 自带的一些模块
环境搭建
- pip 安装需要的模块
- 下载 selenuim 浏览器驱动,不同的浏览器需要下载不同的驱动
- 将下载好的驱动放置环境变量中的文件夹下,也可以放到Python解释器的根目录
具体实现步骤
1. 设置初始化参数、驱动启动参数
import time
from io import BytesIO
from PIL import Image
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from chaojiying import Chaojiying_Client
# 实现点触验证码 以易盾为例 打码平台为超级鹰
class TouchCaptcha(object):
def __init__(self, un, pw, id):
self.url = 'http://dun.163.com/trial/picture-click' # 网址
self.un = un # 打码平台账号
self.pw = pw # 密码
self.id = id # 软件ID
chrom_option = self.set_options()
self.diver = webdriver.Chrome(chrome_options=chrom_option)
self.wait = WebDriverWait(self.diver, 10)
# 设置启动参数
def set_options(self):
option = Options()
option.add_argument("--window-size=1366, 1100")
option.add_argument("disa