Python中常见的反爬机制及其破解方法总结


Posted in Python onJune 10, 2021

一、常见反爬机制及其破解方式

封禁IP,使用cookie等前面文章已经讲过

现在主要将下面的:

​ ~ 验证码
​ —> 文字验证码 —> OCR(光学文字识别)—> 接口 / easyocr
​ 程序自己解决不了的问题就可以考虑使用三方接口(付费/免费)
​ —> 行为验证码 —> 超级鹰
​ ~ 手机号+短信验证码
​ —> 接码平台
​ ~ 动态内容
​ —> JavaScript逆向 —> 找到提供数据的API接口
​ —> 手机抓接口 —> 抓包工具(Charles / Fiddler)
​ —> Selenium直接模拟浏览器操作获取动态内容
​ ~ find_element_by_xxx / find_elements_by_xxx
​ ~ page_source —> 获取包含动态内容的网页源代码
​ —> JavaScript加密和混淆技术 —> 读懂JavaScript是反反爬的前提
​ ~ 字体反爬 / 内容来自于抠图
​ —> 例子

bytes —> 不变字节串 —> 二进制 —> BytesIO
str —> 不变字符串 —> 可阅读的字符 —> StringIO

二、调用三方API接口数据(天行数据)

import requests

for page in range(1, 6):
    response = requests.get(
        'http://api.tianapi.com/topnews/index',
        params={
            'key': 'd5eace66dccd771e36767ce3563efa09',
            'page': page,
            'num': 20,
            'word': '华为',
            'src': '人民日报'
        }
    )
    result = response.json()
    for news in result['newslist']:
        print(news['title'])
        print(news['url'])

三、OCR(光学文字识别)库

python 自带的easyocr库

import easyocr
reader = easyocr.Reader(['ch_sim', 'en'], gpu=False)
print(reader.readtext('./files/captcha.jpg', detail=0))

例子:阿里云邮箱自动登陆

import io

import easyocr

from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

browser = webdriver.Chrome()
browser.set_window_size(1280, 960)
browser.get('http://mail.1000phone.com/')
# 隐式等待(下面的方法在工作时如果取不到就等10秒)
browser.implicitly_wait(10)
# 显式等待
wait = WebDriverWait(browser, 10)
wait.until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, '.login_panel_iframe')))
iframe1 = browser.find_element_by_css_selector('.login_panel_iframe')
# 记录iframe1的位置(相对位置)
x1, y1 = iframe1.location['x'], iframe1.location['y']
# Chrome对象的switch_to属性的frame方法,可以从页面切换到iframe中
browser.switch_to.frame(iframe1)
iframe2 = browser.find_element_by_css_selector('#ding-login-iframe')
x2, y2 = iframe2.location['x'], iframe2.location['y']
browser.switch_to.frame(iframe2)
username_input = browser.find_element_by_css_selector('#username')
# 模拟用户输入
username_input.send_keys('xx@1000phone.com')
password_input = browser.find_element_by_css_selector('#password')
password_input.send_keys('xxxxx!!')
# 创建一个等待对象
wait = WebDriverWait(browser, 10)
wait.until(expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, '#login_checkcode_ico')))
captcha_img = browser.find_element_by_css_selector('#login_checkcode_ico')
# WebElement对象的size属性代表元素宽度和高度,location属性代表元素在窗口中的位置
size, location = captcha_img.size, captcha_img.location
x3, y3, width, height = location['x'], location['y'], size['width'], size['height']
# 截取整个浏览器窗口的图片获得图片的二进制数据
image_data = browser.get_screenshot_as_png()
# bytes(只读字节串) ----> io.BytesIO(可写字节串)---> getvalue() ---> bytes
# str(只读字符串) ----> io.StringIO(可写字符串)---> getvalue() ---> str
browser_image = Image.open(io.BytesIO(image_data))
# 从截图上剪裁出验证码的图片
x, y = x1 + x2 + x3, y1 + y2 + y3
# Windows系统的写法 ---> 如果截图有问题就把坐标写死
# print(x, y, width, height)
checkcode_image = browser_image.crop((x * 1.25, y * 1.25, (x + width) * 1.25, (y + height) * 1.25))
# macOS系统的写法
# checkcode_image = browser_image.crop((x * 2, y * 2, (x + width) * 2, (y + height) * 2))
checkcode_image.save('result.png')
# 通过easyocr做光学文字识别
reader = easyocr.Reader(['en'], gpu=False)
code = reader.readtext('result.png', detail=0)[0]
# 将识别出的验证码输入文本框
checkcode_input = browser.find_element_by_css_selector('#login_checkcode')
checkcode_input.send_keys(code)
login_button = browser.find_element_by_css_selector('#login_submit_btn')
# 模拟用户点击
login_button.click()

四、第三方打码平台(超级鹰打码平台)

补充:需要使用python 自带pillow库

"""
Pillow库 ---> PIL ---> Python Image Library
"""
from PIL import Image, ImageFilter

# 加载图像
guido_image = Image.open('guido.jpg')
# 剪裁
guido_image.crop((80, 40, 310, 350)).show()
# 滤镜
guido_image.filter(ImageFilter.CONTOUR).show()
# 缩略图
guido_image.thumbnail((125, 185))
# 显示图像
guido_image.show()

编写超级鹰打码平台类

from hashlib import md5

import requests


class ChaojiyingClient:

    def __init__(self, username, password, soft_id):
        self.username = username
        password = password.encode('utf8')
        self.password = md5(password).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, image_data, code_type):
        """
        image_data: 图片字节
        code_type: 验证码类型 参考 http://www.chaojiying.com/price.html
        """
        params = {
            'codetype': code_type,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', image_data)}
        response = requests.post(
            url='http://upload.chaojiying.net/Upload/Processing.php',
            data=params,
            files=files,
            headers=self.headers
        )
        return response.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()


if __name__ == '__main__':
    chaojiying = ChaojiyingClient('账户', '密码x', 'ID')  # 用户中心>>软件ID 生成一个替换 96001
    with open('img.png', 'rb') as file:
        image_data = file.read()  # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
        print(chaojiying.post_pic(image_data, 1902))  # 1902 验证码类型  官方网站>>价格体系 3.4+版 print 后要加()

例子:使用超级鹰进行阿里云邮箱自动登陆

import io

import easyocr

from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

from chaojiying import ChaojiyingClient

browser = webdriver.Chrome()
browser.set_window_size(1280, 960)
browser.get('http://mail.1000phone.com/')
# 隐式等待(下面的方法在工作时如果取不到就等10秒)
browser.implicitly_wait(10)
# 显式等待
wait = WebDriverWait(browser, 10)
wait.until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, '.login_panel_iframe')))
iframe1 = browser.find_element_by_css_selector('.login_panel_iframe')
# 记录iframe1的位置(相对位置)
x1, y1 = iframe1.location['x'], iframe1.location['y']
# Chrome对象的switch_to属性的frame方法,可以从页面切换到iframe中
browser.switch_to.frame(iframe1)
iframe2 = browser.find_element_by_css_selector('#ding-login-iframe')
x2, y2 = iframe2.location['x'], iframe2.location['y']
browser.switch_to.frame(iframe2)
username_input = browser.find_element_by_css_selector('#username')
# 模拟用户输入
username_input.send_keys('xxxx.com')
password_input = browser.find_element_by_css_selector('#password')
password_input.send_keys('xxxx!!')
# 创建一个等待对象
wait = WebDriverWait(browser, 10)
wait.until(expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, '#login_checkcode_ico')))
captcha_img = browser.find_element_by_css_selector('#login_checkcode_ico')
# WebElement对象的size属性代表元素宽度和高度,location属性代表元素在窗口中的位置
size, location = captcha_img.size, captcha_img.location
x3, y3, width, height = location['x'], location['y'], size['width'], size['height']
# 截取整个浏览器窗口的图片获得图片的二进制数据
image_data = browser.get_screenshot_as_png()
# bytes(只读字节串) ----> io.BytesIO(可写字节串)---> getvalue() ---> bytes
# str(只读字符串) ----> io.StringIO(可写字符串)---> getvalue() ---> str
browser_image = Image.open(io.BytesIO(image_data))
# 从截图上剪裁出验证码的图片
x, y = x1 + x2 + x3, y1 + y2 + y3
# Windows系统的写法 ---> 如果截图有问题就把坐标写死
# print(x, y, width, height)
checkcode_image = browser_image.crop((x * 1.25, y * 1.25, (x + width) * 1.25, (y + height) * 1.25))
# macOS系统的写法
# checkcode_image = browser_image.crop((x * 2, y * 2, (x + width) * 2, (y + height) * 2))
checkcode_image.save('result.png')
# 通过超级鹰打码平台打码
chaojiying = ChaojiyingClient('账户', '密码', 'ID')
with open('result.png', 'rb') as file:
    image_data = file.read()
    result_dict = chaojiying.post_pic(image_data, 1902)
# 将识别出的验证码输入文本框
checkcode_input = browser.find_element_by_css_selector('#login_checkcode')
checkcode_input.send_keys(result_dict['pic_str'])
login_button = browser.find_element_by_css_selector('#login_submit_btn')
# 模拟用户点击
login_button.click()

五、通过接码平台接收手机验证码(隐私短信平台)

通过隐私短信平台接收验证码(免费)

import re

import bs4
import requests

pattern = re.compile(r'\d{4,6}')

resp = requests.get('https://www.yinsiduanxin.com/china-phone-number/verification-code-16521686439.html')
soup = bs4.BeautifulSoup(resp.text, 'html.parser')
# print(resp.text)
td = soup.select_one('body > div.container > div:nth-child(4) > div:nth-child(3) > div.main > div.layui-row > table > tbody > tr:nth-child(1) > td:nth-child(2)')
results = pattern.findall(td.text)
print(results[0])

到此这篇关于Python中常见的反爬机制及其破解方法总结的文章就介绍到这了,更多相关Python反爬机制及其破解内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python使用正则表达式检测密码强度源码分享
Jun 11 Python
python基础教程之循环介绍
Aug 29 Python
Python中的Matplotlib模块入门教程
Apr 15 Python
Python数据结构与算法之使用队列解决小猫钓鱼问题
Dec 14 Python
解决python3 网络请求路径包含中文的问题
May 10 Python
Python实现在某个数组中查找一个值的算法示例
Jun 27 Python
对Python3 pyc 文件的使用详解
Feb 16 Python
python实现支付宝转账接口
May 07 Python
PyQt5显示GIF图片的方法
Jun 17 Python
用python求一个数组的和与平均值的实现方法
Jun 29 Python
python Tkinter模块使用方法详解
Apr 07 Python
讲解Python实例练习逆序输出字符串
May 06 Python
Pytorch可视化的几种实现方法
OpenCV-Python实现怀旧滤镜与连环画滤镜
OpenCV-Python实现轮廓的特征值
Jun 09 #Python
再也不用花钱买漫画!Python爬取某漫画的脚本及源码
Jun 09 #Python
Python的这些库,你知道多少?
OpenCV-Python使用cv2实现傅里叶变换
Python合并多张图片成PDF
Jun 09 #Python
You might like
深入理解PHP原理之异常机制
2010/08/21 PHP
PHP学习笔记之二 php入门知识
2011/01/12 PHP
PHP autoload与spl_autoload自动加载机制的深入理解
2013/06/05 PHP
对PHP新手的一些建议(PHP学习经验总结)
2014/08/20 PHP
JS动态获取当前时间,并写到特定的区域
2013/05/03 Javascript
jQuery获取checkbox选中的值
2016/01/28 Javascript
JavaScript兼容浏览器FF/IE技巧
2016/08/14 Javascript
jquery.validate表单验证插件使用方法解析
2016/11/07 Javascript
详解Node.js:events事件模块
2016/11/24 Javascript
微信小程序 video详解及简单实例
2017/01/16 Javascript
vue.js实现条件渲染的实例代码
2017/06/22 Javascript
详解vue数组遍历方法forEach和map的原理解析和实际应用
2018/11/15 Javascript
Vue中函数防抖节流的理解及应用实现
2020/04/24 Javascript
[05:13]TI4 中国战队 机场出征!!
2014/07/07 DOTA
使用Python的内建模块collections的教程
2015/04/28 Python
Python写入CSV文件的方法
2015/07/08 Python
Django中ORM表的创建和增删改查方法示例
2017/11/15 Python
python循环嵌套的多种使用方法解析
2019/11/29 Python
使用Python爬取弹出窗口信息的实例
2020/03/14 Python
Windows下Anaconda安装、换源与更新的方法
2020/04/17 Python
python 实现数据库中数据添加、查询与更新的示例代码
2020/12/07 Python
详解python使用金山词霸的翻译功能(调试工具断点的使用)
2021/01/07 Python
HTML5中的Scoped属性使用实例
2014/04/23 HTML / CSS
HTML5 Canvas实现图片缩放、翻转、颜色渐变的代码示例
2016/02/28 HTML / CSS
澳大利亚领先的女帽及配饰公司:Morgan&Taylor
2019/12/01 全球购物
斯洛伐克最大的婴儿食品和用品网上商店:Feedo.sk
2020/12/21 全球购物
加拿大探亲邀请信
2014/01/28 职场文书
历史学专业求职信
2014/06/19 职场文书
信用卡工资证明格式
2014/09/13 职场文书
上班时间打瞌睡检讨书
2014/09/26 职场文书
化验室岗位职责
2015/02/14 职场文书
施工员岗位职责范本
2015/04/11 职场文书
通知的写法
2015/04/23 职场文书
培训简讯范文
2015/07/20 职场文书
关于Python使用turtle库画任意图的问题
2022/04/01 Python
悬疑名作《朋友游戏》动画无字ED宣传片 新角色公开
2022/04/13 日漫