爬虫—图形验证码获取
获取验证码图片步骤
1. 使用selenium操作谷歌浏览器,打开目标网站
2. 对目标网站进行截图,并将图片保存到本地
3. 获取验证码元素节点在屏幕上的位置,即横纵坐标
4. 使用Image库读取保存的截图
5. 使用pillow模块抠出大图中的验证码 只截取元素节点位置对应部分
导入所需库和打开目标网站
from selenium import webdriver
from selenium.webdriver.common.by import By
from PIL import Image
bro = webdriver.Chrome(executable_path='./chromedriver.exe') # 打开浏览器
bro.get('https://www.chaojiying.com/apiuser/login/') # 打开目标网站
bro.implicitly_wait(10) # 隐士等待
bro.maximize_window() # 将浏览器全屏
网页截图保存
bro.save_screenshot('screenshot.png') # 网页截图,保存
获取验证码元素位置
# 根据css选择器找验证码元素
code = bro.find_element(By.CSS_SELECTOR,'body > div.wrapper_danye > div > div.content_login > div.login_form > form > div > img')
# 左上角的位置
left = code.location['x'] # 1110
top = code.location['y'] # 291
# 右下角的位置
right = code.size['width'] + left # 1290
bottom = code.size['height'] + top # 341
读取截图、截取验证码图片和保存验证码图片
img = Image.open('screenshot.png') # 读取全屏截图
img = img.crop((left, top, right, bottom)) # 截取验证码图片
img.save('code.png') # 保存图片
代码整合
from selenium import webdriver
from selenium.webdriver.common.by import By
from PIL import Image
bro = webdriver.Chrome(executable_path='./chromedriver.exe') # 打开浏览器
bro.get('https://www.chaojiying.com/apiuser/login/') # 打开目标网站
bro.implicitly_wait(10) # 隐士等待
bro.maximize_window() # 将浏览器全屏
bro.save_screenshot('screenshot.png') # 网页截图,保存
# 根据css选择器找验证码元素
code = bro.find_element(By.CSS_SELECTOR,'body > div.wrapper_danye > div > div.content_login > div.login_form > form > div > img')
# 左上角的位置
left = code.location['x'] # 1110
top = code.location['y'] # 291
# 右下角的位置
right = code.size['width'] + left # 1290
bottom = code.size['height'] + top # 341
img = Image.open('screenshot.png') # 读取全屏截图
img = img.crop((left, top, right, bottom)) # 截取验证码图片
img.save('code.png') # 保存图片
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)