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中的struct模块
Apr 28 Python
基python实现多线程网页爬虫
Sep 06 Python
python 拷贝特定后缀名文件,并保留原始目录结构的实例
Apr 27 Python
pandas使用get_dummies进行one-hot编码的方法
Jul 10 Python
超简单使用Python换脸实例
Mar 27 Python
python3.6使用tkinter实现弹跳小球游戏
May 09 Python
Python socket 套接字实现通信详解
Aug 27 Python
Django 404、500页面全局配置知识点详解
Mar 10 Python
django-csrf使用和禁用方式
Mar 13 Python
pip install 使用国内镜像的方法示例
Apr 03 Python
Python捕获异常堆栈信息的几种方法(小结)
May 18 Python
python实现剪贴板的操作
Jul 01 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
ThinkPHP中pathinfo的访问模式、路径访问模式及URL重写总结
2014/08/23 PHP
php实现的常见排序算法汇总
2014/09/08 PHP
PHP从FLV文件获取视频预览图的方法
2015/03/12 PHP
PHP实现上传图片到 zimg 服务器
2016/10/19 PHP
PHP快速推送微信模板消息
2017/04/14 PHP
PHP实现的mysql主从数据库状态检测功能示例
2017/07/20 PHP
thinkPHP5框架auth权限控制类与用法示例
2018/06/12 PHP
php微信开发之关注事件
2018/06/14 PHP
js 数据类型转换总结笔记
2011/01/17 Javascript
jquery自定义属性(类型/属性值)
2013/05/21 Javascript
jQuery仅用3行代码实现的显示与隐藏功能完整实例
2015/10/08 Javascript
JavaScript中日期的相关操作方法总结
2015/10/24 Javascript
详解JavaScript中的Unescape()和String() 函数
2015/11/09 Javascript
javascript淘宝主图放大镜功能
2016/10/20 Javascript
JS获取数组中出现次数最多及第二多元素的方法
2017/10/27 Javascript
微信小程序 scroll-view实现锚点滑动的示例
2017/12/06 Javascript
vue 项目接口管理的实现
2019/01/17 Javascript
javascript canvas检测小球碰撞
2020/04/17 Javascript
微信小程序之导航滑块视图容器功能的实现代码(简单两步)
2020/06/19 Javascript
了不起的11个JavaScript代码重构最佳实践小结
2021/01/11 Javascript
[10:04]国际邀请赛采访专栏:DK.Farseer,mouz.Black^,采访员Josh专访
2013/08/05 DOTA
numpy自动生成数组详解
2017/12/15 Python
Python3.6安装及引入Requests库的实现方法
2018/01/24 Python
pandas.DataFrame 根据条件新建列并赋值的方法
2018/04/08 Python
提升Python程序性能的7个习惯
2019/04/14 Python
python multiprocessing模块用法及原理介绍
2019/08/20 Python
如何基于Python实现自动扫雷
2020/01/06 Python
解决TensorFlow训练内存不断增长,进程被杀死问题
2020/02/05 Python
pytorch查看通道数 维数 尺寸大小方式
2020/05/26 Python
对Pytorch 中的contiguous理解说明
2021/03/03 Python
Html5页面上如何禁止手机虚拟键盘弹出
2020/03/19 HTML / CSS
Smashbox官网:美国知名彩妆品牌
2017/01/05 全球购物
正隆泰信息技术有限公司上机题
2012/06/14 面试题
做一个有道德的人活动实施方案
2014/08/23 职场文书
法英专业大学生职业生涯规划书范文
2014/09/22 职场文书
Java线程的6种状态与生命周期
2022/05/11 Java/Android