本文主要是介绍Python爬虫实战 | (16) 破解简书登录点触验证码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在本篇博客中,我们将使用selenium模拟登录简书网站,破解其登陆时的滑动验证码。
我们需要使用验证码识别服务平台。超级鹰,来帮助我们破解点触验证码。下面的chaojiying.py文件用于调用超级鹰服务,帮助我们破解点触或图片验证码,直接照搬就好了:
import requests
from hashlib import md5#使用超级鹰来进行图片验证码和点触验证码的识别
class Chaojiying(object):def __init__(self, username, password, soft_id):self.username = usernameself.password = md5(password.encode('utf-8')).hexdigest()self.soft_id = soft_idself.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 = USERNAMEself.password = PASSWARDself.chaojiying = Chaojiying(CHAOJIYING_USERNAME, CHAOJIYING_PASSWORD, CHAOJIYING_SOFT_ID)def __del__(self):self.browser.close()def login_successfully(self):passdef touch_click_verify(self):passdef touch_click_words(self,locations):passdef get_points(self,captcha_result):passdef get_touclick_element(self):passdef get_touclick_image(self,name='captcha.png'):passdef get_login_btn(self):passdef open(self):passdef 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)# 找到用户名输入框'''<input placeholder="手机号或邮箱" type="text" name="session[email_or_mobile_number]" id="session_email_or_mobile_number">'''username = self.wait.until(EC.presence_of_element_located((By.ID, 'session_email_or_mobile_number')))# 找到密码输入框'''<input placeholder="密码" type="password" name="session[password]" id="session_password">'''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 class="sign-in-button" id="sign-in-form-submit-btn" type="button"><span id="sign-in-loading"></span>登录</button>'''button = self.wait.until(EC.element_to_be_clickable((By.ID,'sign-in-form-submit-btn')))return button
获取点触验证码图片:
def get_touclick_element(self):"""获取验证图片元素:return: 图片元素"""# 获取整个验证图片'''<div class="geetest_holder geetest_silver" style="width: 100%; display: block; opacity: 1;"><div class="geetest_widget"><div class="geetest_head"><div class="geetest_tips"><div class="geetest_tip_content">请在下图<span class="geetest_mark">依次</span>点击:</div><div class="geetest_tip_img" aria-hidden="true" style="display: block; background-image: url("https://static.geetest.com/nerualpic/word_l1_zh_2019.06.10/starry_night/11765df8573a797e0c5951eb781ab68f.jpg?challenge=628d53ef8ff2f9c9a4b006f103d60067"); width: 116px; height: 40px; right: -116px; top: -10px;"></div></div><div class="geetest_atips"><div class="geetest_atip_content"></div><div class="geetest_tip_text"><div class="geetest_word1"><span class="">1</span></div><div class="geetest_word2"><span class="">2</span></div><div class="geetest_word3"><span class="">3</span></div><div class="geetest_word4"><span class="">4</span></div><div class="geetest_word5"><span class="">5</span></div><div class="geetest_word6"><span class="">6</span></div></div></div><div class="geetest_tip_space"></div></div><div class="geetest_table_box"><div class="geetest_window"><div class="geetest_item geetest_big_item" style="width: 95.8%; padding-bottom: 95.8%;"><div class="geetest_item_loading"><div class="geetest_item_loading_icon"></div><div class="geetest_item_loading_tip">加载中...</div></div><div class="geetest_item_wrap"><img class="geetest_item_img" aria-hidden="true" src="https://static.geetest.com/nerualpic/word_l1_zh_2019.06.10/starry_night/11765df8573a797e0c5951eb781ab68f.jpg?challenge=628d53ef8ff2f9c9a4b006f103d60067" style="right: 0px; top: 0px; width: 100%; height: 112%;"></div></div></div><div class="geetest_result_tip"></div></div><div class="geetest_panel"><div class="geetest_small" tabindex="-1" style="outline: none; font-size: 12px;"><a class="geetest_close" href="javascript:;" tabindex="-1"><div class="geetest_close_tip">关闭验证</div></a><a class="geetest_refresh" href="javascript:;" tabindex="-1"><div class="geetest_refresh_tip">刷新验证</div></a><a class="geetest_feedback" tabindex="-1" style="display: none;"><div class="geetest_feedback_tip">帮助反馈</div></a><a class="geetest_voice"><div class="geetest_voice_tip"></div></a></div><a class="geetest_commit" href="javascript:;"><div class="geetest_commit_tip">确认</div></a></div></div></div>'''element = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,'.geetest_holder')))return elementdef 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:"""'''<div class="geetest_commit_tip">确认</div>'''button = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME,'geetest_commit_tip')))button.click()
判断登录是否成功,如果成功,会有一个写文章按钮:
def login_successfully(self):"""判断登陆是否成功:return:"""'''<a class="btn write-btn" target="_blank" href="/writer#/"><i class="iconfont ic-write"></i>写文章
</a>'''try:return bool(WebDriverWait(self.browser,5).until(EC.presence_of_element_located((By.CSS_SELECTOR,'.write-btn'))))except TimeoutException:return False
完整项目
这篇关于Python爬虫实战 | (16) 破解简书登录点触验证码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!