Python爬虫实战 | (16) 破解简书登录点触验证码

在本篇博客中,我们将使用selenium模拟登录简书网站,破解其登陆时的滑动验证码。

我们需要使用验证码识别服务平台。超级鹰,来帮助我们破解点触验证码。下面的chaojiying.py文件用于调用超级鹰服务,帮助我们破解点触或图片验证码,直接照搬就好了:

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/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
        }

    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()

程序主体框架:

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

#简书用户名、密码
USERNAME = ''
PASSWARD = ''
#超级鹰用户名、密码、软件ID(需要注册)
CHAOJIYING_USERNAME = ''
CHAOJIYING_PASSWORD = ''
CHAOJIYING_SOFT_ID = 
CHAOJIYING_KIND = 9004 #验证码类型 用于破解点触验证码 具体可见官网

class JianShuLogin():

    def __init__(self):
        self.url = 'https://www.jianshu.com/sign_in'
        self.browser = webdriver.Chrome()
        # 显示等待
        self.wait = WebDriverWait(self.browser, 20)
        self.username = USERNAME
        self.password = PASSWARD
        self.chaojiying = Chaojiying(CHAOJIYING_USERNAME, CHAOJIYING_PASSWORD, CHAOJIYING_SOFT_ID)

    def __del__(self):
        self.browser.close()

    def login_successfully(self):
        pass
    
    def touch_click_verify(self):
        pass
    
    def touch_click_words(self,locations):
        pass
    
    def get_points(self,captcha_result):
        pass
    
    def get_touclick_element(self):
        pass
    
    def get_touclick_image(self,name='captcha.png'):
        pass
    
    def get_login_btn(self):
        pass
    
    def open(self):
        pass
    
    def login(self):
        """
        破解入口
        :return:
        """
        #打开登陆界面 输入用户名和密码
        self.open()
        #找到登陆按钮
        button = self.get_login_btn()
        #点击
        button.click()

        #获取点触验证码图片
        image = self.get_touclick_image()
        bytes_array = BytesIO()
        image.save(bytes_array, format='PNG')

        # 识别验证码
        result = self.chaojiying.post_pic(bytes_array.getvalue(), CHAOJIYING_KIND)
        print(result)

        # 获取点击的位置
        locations = self.get_points(result)

        # 依次进行点击
        self.touch_click_words(locations)
        # 找到并点击确认按钮
        self.touch_click_verify()

        # 判断是否成功
        if self.login_successfully():
            print('登录成功')
        else:  # 可能不成功 重来
            self.chaojiying.report_error(result['pic_id'])
            self.login()

if __name__ == '__main__':
    login = JianShuLogin()
    login.login()

打开网页,输入用户名和密码:

  def open(self):
        """
        打开网页输入用户名和密码
        :return: None
        """
        self.browser.get(self.url)
        # 找到用户名输入框
        '''
        
        '''
        username = self.wait.until(EC.presence_of_element_located((By.ID, 'session_email_or_mobile_number')))
        # 找到密码输入框
        '''
        
        '''
        passward = self.wait.until(EC.presence_of_element_located((By.ID, 'session_password')))
        # 输入用户名和密码
        username.send_keys(self.username)
        passward.send_keys(self.password)

找到登录按钮:

    def get_login_btn(self):
        """
        找到登陆按钮
        :return:
        """
        '''
        
        '''
        button = self.wait.until(EC.element_to_be_clickable((By.ID,'sign-in-form-submit-btn')))
        return button

获取点触验证码图片:

    def get_touclick_element(self):
        """
        获取验证图片元素
        :return: 图片元素
        """
        # 获取整个验证图片
        '''
        
请在下图依次点击:
1
2
3
4
5
6
加载中...
''' element = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'.geetest_holder'))) return element def get_touclick_image(self,name='captcha.png'): """ 获取点触验证码图片 :param name: :return: 图片对象 """ im = self.get_touclick_element() time.sleep(2) im.screenshot('captcha_.png') captcha = Image.open('captcha_.png') print(im.size) # 改变截图的大小 和原图一致 captcha = captcha.resize((im.size['width'], im.size['height'])) captcha.save('captcha_resize.png') return captcha

解析超级鹰识别结果,获取点击坐标:

 def get_points(self,captcha_result):
        """
        解析识别结果
        :param captcha_result: 识别结果
        :return:转换后的结果
        """
        # 获取点击的坐标
        groups = captcha_result.get('pic_str').split('|')
        locations = [[int(number) for number in group.split(',')] for group in groups]
        return locations

根据坐标,点击验证图片:

 def touch_click_words(self,locations):
        """
        点击验证图片
        :param locations: 点击位置
        :return:
        """
        for location in locations:
            print(location)
            ActionChains(self.browser).move_to_element_with_offset(self.get_touclick_element(), location[0],
                                                                   location[1]).click().perform()
            time.sleep(1)

最后点击确认按钮:

 def touch_click_verify(self):
        """
        点击确认按钮
        :return:
        """
        '''
        
确认
''' button = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME,'geetest_commit_tip'))) button.click()

判断登录是否成功,如果成功,会有一个写文章按钮:

Python爬虫实战 | (16) 破解简书登录点触验证码_第1张图片

    def login_successfully(self):
        """
        判断登陆是否成功
        :return:
        """
        '''
        
        写文章

        '''
        try:
            return bool(
                WebDriverWait(self.browser,5).until(EC.presence_of_element_located((By.CSS_SELECTOR,'.write-btn')))
            )
        except TimeoutException:
            return  False

完整项目

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(Python爬虫实战 | (16) 破解简书登录点触验证码)