Python3爬虫实战【点触验证码】 — 模拟登陆bilibili

模拟登录哔哩哔哩

爬虫时间:2020-08-30
请求链接:https://passport.bilibili.com/login
实现目标:模拟登陆哔哩哔哩
涉及知识:点触验证码的攻克、自动化测试工具 Selenium 的使用,超级鹰打码平台的使用
完整代码:https://github.com/dateolive/python-/tree/master/bilibili
学习过程中的爬虫GitHub库:https://github.com/dateolive/python-

爬虫思路如下:

  • 利用自动化爬虫工具 Selenium 模拟点击输入等操作来进行登录
  • 分析页面,获取点触验证码的点触图片,通过将图片发送给超级鹰打码平台识别后获取坐标信息
  • 根据超级鹰返回的数据,模拟坐标的点选,即可实现登录

一.准备工作

在开始之前,需要先注册一个超级鹰账号并申请一个软件ID,注册页面链接为:https://www.chaojiying.com/user/reg/,注册完成后需要在后台添加一个软件ID,进行充值获得积分,一般充一块钱就可以了。

二.爬虫构建

1.首先我可以到官方网站下载对应的 Python API,链接为:https://www.chaojiying.com/api-14.html ,我这里使用了崔庆才大大修改后的超级鹰api

代码如下:

import requests
from hashlib import md5


class Chaojiying(object):

    def __init__(self, username, password, soft_id):
        self.username = username
        self.password = md5(password.encode('utf-8')).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def post_pic(self, im, codetype):
        """
        im: 图片字节
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files,
                          headers=self.headers)
        return r.json()

    def report_error(self, im_id):
        """
        im_id:报错题目的图片ID
        """
        params = {
            'id': im_id,
        }
        params.update(self.base_params)
        r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)
        return r.json()

2.初始化函数

def __init__(self):
    self.url = 'https://passport.bilibili.com/login'
    self.browser = webdriver.Chrome()
    self.browser.maximize_window()
    self.wait = WebDriverWait(self.browser, 20)
    self.username = USERNAME
    self.password = PASSWORD
这里定义了发起请求的url、用户名、密码等全局变量,实例化 Chrome 浏览器、设置浏览器分辨率最大化、用户名、密码、同时也设置等待超时

3.登录函数

def open(self):
    """
    打开网页输入用户名密码
    :return: None
    """
    self.browser.get(self.url)
    user = self.wait.until(EC.presence_of_element_located((By.ID, 'login-username')))
    password = self.wait.until(EC.presence_of_element_located((By.ID, 'login-passwd')))
    user.send_keys(self.username)
    password.send_keys(self.password)
    login_btn = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a.btn.btn-login')))
    # 随机暂停几秒
    time.sleep(random.random() * 3)
    # 点击登陆按钮
    login_btn.click()
等待账号输入框和密码输入框对应的 ID 节点加载出来,然后获取对应节点,其中账号输入框 id="login-username",密码输框 id="login-passwd",通过调用 send_keys() 方法输入账号和密码,接着获取登录按钮 class="btn btn-login",设置暂停时间,最后调用 click() 方法实现登录按钮的点击。

4.点触验证码的处理

def pick_code(self):
    time.sleep(3)
    pick_img_label = self.browser.find_element_by_css_selector('img.geetest_item_img')  # 获取点触图片标签
    src = pick_img_label.get_attribute('src')  # 获取点触图片链接
    img_content = requests.get(src).content  # 获取图片二进制内容
    f = BytesIO()
    f.write(img_content)
    img0 = Image.open(f)  # 将图片以文件的形式打开,主要是为了获取图片的大小
    scale = [pick_img_label.size['width'] / img0.size[0],
             pick_img_label.size['height'] / img0.size[1]]  # 获取图片与浏览器该标签大小的比例
    cjy = Chaojiying(CHAOJIYING_USERNAME, CHAOJIYING_PASSWORD, CHAOJIYING_SOFT_ID)
    result = cjy.post_pic(img_content, '9005')  # 发送图片并获取结果
    if result['err_no'] == 0:  # 对结果进行分析
        position = result['pic_str'].split('|')  # position = ['110,234','145,247','25,185']
        position = [[int(j) for j in i.split(',')] for i in position]  # position = [[110,234],[145,247],[25,185]]
        for items in position:  # 模拟点击
            ActionChains(self.browser).move_to_element_with_offset(pick_img_label, items[0] * scale[0],
                                                                   items[1] * scale[1]).click().perform()
            time.sleep(1)
        time.sleep(2)
        # 点击登录
        certern_btn = self.browser.find_element_by_css_selector('div.geetest_commit_tip')
        certern_btn.click()
    return cjy, result
通过css选择器,找到点触图片的标签,获取图标的src链接,对图片处理发送给超级鹰后台并获取结果,对结果进行分析,模拟坐标的点选,即可实现登录。

三.爬虫完整代码

import random
import time
from io import BytesIO
import requests
from PIL import Image
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from chaojiying import Chaojiying

USERNAME = 'b站账号'
PASSWORD = '密码'

CHAOJIYING_USERNAME = '超级鹰账号'
CHAOJIYING_PASSWORD = '密码'
CHAOJIYING_SOFT_ID = 907581
CHAOJIYING_KIND = 9004


class CrackTouClick():
    def __init__(self):
        self.url = 'https://passport.bilibili.com/login'
        self.browser = webdriver.Chrome()
        self.browser.maximize_window()
        self.wait = WebDriverWait(self.browser, 20)
        self.username = USERNAME
        self.password = PASSWORD


    def open(self):
        """
        打开网页输入用户名密码
        :return: None
        """
        self.browser.get(self.url)
        user = self.wait.until(EC.presence_of_element_located((By.ID, 'login-username')))
        password = self.wait.until(EC.presence_of_element_located((By.ID, 'login-passwd')))
        user.send_keys(self.username)
        password.send_keys(self.password)
        login_btn = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a.btn.btn-login')))
        # 随机暂停几秒
        time.sleep(random.random() * 3)
        # 点击登陆按钮
        login_btn.click()

    def pick_code(self):
        time.sleep(3)
        pick_img_label = self.browser.find_element_by_css_selector('img.geetest_item_img')  # 获取点触图片标签
        src = pick_img_label.get_attribute('src')  # 获取点触图片链接
        img_content = requests.get(src).content  # 获取图片二进制内容
        f = BytesIO()
        f.write(img_content)
        img0 = Image.open(f)  # 将图片以文件的形式打开,主要是为了获取图片的大小
        scale = [pick_img_label.size['width'] / img0.size[0],
                 pick_img_label.size['height'] / img0.size[1]]  # 获取图片与浏览器该标签大小的比例
        cjy = Chaojiying(CHAOJIYING_USERNAME, CHAOJIYING_PASSWORD, CHAOJIYING_SOFT_ID)
        result = cjy.post_pic(img_content, '9005')  # 发送图片并获取结果
        if result['err_no'] == 0:  # 对结果进行分析
            position = result['pic_str'].split('|')  # position = ['110,234','145,247','25,185']
            position = [[int(j) for j in i.split(',')] for i in position]  # position = [[110,234],[145,247],[25,185]]
            for items in position:  # 模拟点击
                ActionChains(self.browser).move_to_element_with_offset(pick_img_label, items[0] * scale[0],
                                                                       items[1] * scale[1]).click().perform()
                time.sleep(1)
            time.sleep(2)
            # 点击登录
            certern_btn = self.browser.find_element_by_css_selector('div.geetest_commit_tip')
            certern_btn.click()
        return cjy, result

    def crack(self):
        """
        破解入口
        :return: None
        """
        self.open()
        self.pick_code()
if __name__ == '__main__':
    crack = CrackTouClick()
    crack.crack()

 

点赞

发表评论

昵称和uid可以选填一个,填邮箱必填(留言回复后将会发邮件给你)
tips:输入uid可以快速获得你的昵称和头像