脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - selenium+python实现1688网站验证码图片的截取功能

selenium+python实现1688网站验证码图片的截取功能

2021-03-27 00:46Kosmoo Python

这篇文章主要介绍了selenium+python实现1688网站验证码图片的截取,需要的朋友可以参考下

1. 背景

•在1688网站爬取数据时,如果访问过于频繁,无论用户是否已经登录,就会弹出如下所示的验证码登录框。

selenium+python实现1688网站验证码图片的截取功能

一般的验证码是类似于如下的元素(通过链接单独加载进页面,而不是嵌入图片元素):

python" id="highlighter_550467">
?
1
<img id="j_checkcodeimg1" width="100" height="30" onmousedown="return false;" src="//pin.aliyun.com/get_img?identity=sm-searchweb2&sessionid=9c3a51d81de07ddf1bfd9bbc70863b0f&type=default&t=1511315617645">

•一般来说,获取验证码图片有两种方式:

•第一,拿到上面验证码的图片链接:src=”//pin.aliyun.com/get_img?identity=sm-searchweb2&sessionid=9c3a51d81de07ddf1bfd9bbc70863b0f&type=default&t=1511315617645”,但是这种方式有时候行不通。因为有时候会发现当前的验证码和通过提取出来的url链接打开的验证码,内容是不一样的,其内容不断发生变化。

•第二,利用selenium先进行可视区域的截屏,然后定位验证码元素的位置以及大小,然后利用image(pil模块中)进行裁剪,得到验证码图片,然后送往验证码模块或者打码平台处理。

2. 环境

•python 3.6.1
•系统:win7
•ide:pycharm
•安装过chrome浏览器
•配置好chromedriver
•selenium 3.7.0

3. 分析网页结构

selenium+python实现1688网站验证码图片的截取功能

通过分析网页源代码,我们可以得出以下结论:

•这个验证码登录框是通过iframe嵌入到网页中的。
•页面中不止这一个iframe嵌套。
•这个验证码iframe有很明显的特征:id=”sufei-dialog-content”和src=”https://sec.1688.com/query.htm?……”

?
1
<iframe id="sufei-dialog-content" frameborder="none" src="https://sec.1688.com/query.htm?style=mini&smapp=searchweb2&smpolicy=searchweb2-rpcasyncall-anti_spider-checkcode&smcharset=gbk&smtag=mtixlje1lji2ljizmywznte1mta4mji5lgflnge1zgi1ytq4ndq3ntniyzy5otzlzmu1owe3njhm&smreturn=https%3a%2f%2fs.1688.com%2fselloffer%2frpc_async_render.jsonp%3fkeywords%3d%25cf%25b4%25cd%25eb%25b2%25bc%26startindex%3d0%26n%3dy%26pagesize%3d60%26rpcflag%3dnew%26async%3dtrue%26templateconfigname%3dmarketofferresult%26enableasync%3dtrue%26qrwredirectenabled%3dfalse%26filterp4pids%3d1245873517%252c561786598916%252c559726907082%252c523166432402%252c557139543735%252c529784793813%252c543923733444%252c560590249743%26asynccount%3d20%26_pagename_%3dmarket%26offset%3d9%26uniqfield%3dpic_tag_id%26leftp4pids%3d%26callback%3djquery18305735956012709345_1511341604992%26beginpage%3d48%26_%3d1511341615310&smsign=xkm5xsgakiixvokhv1vsyg%3d%3d" cd_frame_id_="c4ae94ef2bea60f0b4729f319df59251"></iframe>

4. 代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# 前提是,在程序启动时,对浏览器窗口大小进行了设置
from selenium import webdriver
import time
from pil import image
browser = webdriver.chrome()
# 根据桌面分辨率来定,主要是为了抓到验证码的截屏,验证码需要出现在可视区域中
browser.set_window_size(960, 960)
# 处理验证码弹窗
def captchahandler(browser, damatuinstance):
  iframelst = browser.find_elements_by_tag_name('iframe')
  print(f"captchahandler: enter , iframelst = {iframelst}")
  for iframe in iframelst:
    iframeid = iframe.get_attribute('id')
    iframesrc = iframe.get_attribute('src')
    print(f"captchahandler: iframeid = {iframeid}, iframesrc = {iframesrc}")
    # 找到验证码登录iframe
    if iframeid and iframeid.find('dialog') != -1:
      if iframesrc and iframesrc.find(r'sec.1688.com') != -1:
        # 拿到iframe的宽度和高度
        framewidth = iframe.size['width']
        frameheight = iframe.size['height']
        # 代表验证码区域可见
        # 某些情况下,会出现验证码框不弹出,而iframe还在的暂态
        if framewidth > 0 and frameheight > 0:
          print(f"验证码弹出, 进行处理, framewidth = {framewidth}, frameheight = {frameheight}")
          # 截屏,在chrome中截取的是可视区域,而不是整个html页面
          # 前提是当前project下已经创建了clawerimgs目录
          browser.get_screenshot_as_file('clawerimgs/screenshot.png')
          # 先拿到iframe在整个可视页面(也就是上面的截屏)中的相对位置,因为前面对页面的窗口大小进行了设置960 x 960
          # location_once_scrolled_into_view 拿到的是相对于可视区域的坐标
          # location 拿到的是相对整个html页面的坐标
          framex = int(iframe.location_once_scrolled_into_view['x'])
          framey = int(iframe.location_once_scrolled_into_view['y'])
          print(f"captchahandler: framex = {framex}, framey = {framey}, framewidth = {framewidth}, frameheight = {frameheight}")
          # 获取指定元素位置,先拿iframe元素的图片
          left = framex
          top = framey
          right = framex + framewidth
          bottom = framey + frameheight
          # 通过image处理图像,截取frame的图片 ———— 无意义,只是做经验总结
          imgframe = image.open('clawerimgs/screenshot.png')
          imgframe = imgframe.crop((left, top, right, bottom)) # 裁剪
          imgframe.save('clawerimgs/iframe.png')
          # 切换到验证码弹出框的frame,不然无法获取到验证码元素,因为验证码元素是在iframe中
          browser.switch_to.frame(iframe)
          # ------获取验证码图片,第一种方法:在frame区域截取
          # 获取指定元素位置
          captchaelem = browser.find_element_by_xpath("//img[contains(@id, 'checkcodeimg')]")
          # 因为验证码在frame中没有缩放,直接取验证码图片的绝对坐标
          # 这个坐标是相对于它所属的frame的,而不是整个可视区域
          captchax = int(captchaelem.location['x'])
          captchay = int(captchaelem.location['y'])
          # 取验证码的宽度和高度
          captchawidth = captchaelem.size['width']
          captchaheight = captchaelem.size['height']
          captcharight = captchax + captchawidth
          captchabottom = captchay + captchaheight
          print(f"captchahandler: 1 captchax = {captchax}, captchay = {captchay}, captchawidth = {captchawidth}, captchaheight = {captchaheight}")
          # 通过image处理图像,第一种方法:在frame区域截取
          imgobject = image.open('clawerimgs/iframe.png')
          imgcaptcha = imgobject.crop((captchax, captchay, captcharight, captchabottom))   # 裁剪
          imgcaptcha.save('clawerimgs/captcha1.png')
          # ------获取验证码图片,第二种方法:在整个可视区域截取。 就要加上这个iframe的便宜量
          captchaelem = browser.find_element_by_xpath("//img[contains(@id, 'checkcodeimg')]")
          captchax = int(captchaelem.location['x']) + framex
          captchay = int(captchaelem.location['y']) + framey
          captchawidth = captchaelem.size['width']
          captchaheight = captchaelem.size['height']
          captcharight = captchax + captchawidth
          captchabottom = captchay + captchaheight
          print(f"captchahandler: 2 captchax = {captchax}, captchay = {captchay}, captchawidth = {captchawidth}, captchaheight = {captchaheight}")
          # 通过image处理图像,第二种方法:在整个可视区域截取
          imgobject = image.open('clawerimgs/screenshot.png')
          imgcaptcha = imgobject.crop((captchax, captchay, captcharight, captchabottom))    # 裁剪
          imgcaptcha.save('clawerimgs/captcha2.png')

5. 结果展示

•整个可视区域:screenshot.png

selenium+python实现1688网站验证码图片的截取功能

•验证码登录框iframe区域:iframe.png

selenium+python实现1688网站验证码图片的截取功能

•相对于iframe截取的验证码图片:captcha1.png

selenium+python实现1688网站验证码图片的截取功能

•相对于整个可视区域截取的验证码图片:captcha2.png

selenium+python实现1688网站验证码图片的截取功能

6. 拓展

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 摘自https://www.cnblogs.com/my8100/p/7225408.html
chrome
  default:
    location 不滚动,直接返回相对整个html的坐标 {'x': 15.0, 'y': 129.0}
    location_once_scrolled_into_view 返回相对可视区域的坐标(改变浏览器高度,可以观察到底部元素底部对齐后y的变化)
      顶部/底部元素 完全可见不滚动,{u'x': 15, u'y': 60}
      顶部元素部分可见或完全不可见都会滚动到 顶部对齐 {u'x': 15, u'y': 0} account-wall
      底部元素部分可见或完全不可见都会滚动到 底部对齐 {u'x': 15, u'y': 594} theme-list
  frame:
    location 不滚动,直接返回相对frame即当前相应内层html的坐标{'x': 255.0, 'y': 167.0} captcha_frame 的 lc-refresh
    location_once_scrolled_into_view 返回相对可视区域的坐标
      完全可见不滚动{u'x': 273, u'y': 105}
      部分可见或完全不可见滚动到 顶部对齐 {u'x': 273, u'y': 0}
  firefox
    default:
      顶部元素 底部元素
        location 不滚动,直接返回相对整个html的坐标 {'x': 15.0, 'y': 130.0} {'x': 15.0, 'y': 707.0}
        location_once_scrolled_into_view 返回相对可视区域的坐标(y=1足以说明)
          可见不可见 都滚动到顶部对齐 {'x': 15.0, 'y': 1.0} {'x': 15.0, 'y': 1.0}
          如果下拉条直到底部,底部元素仍然无法顶部对齐 {'x': 15.0, 'y': 82.0}
    frame:
      location 不滚动,都是相对frame即当前相应html的坐标{'x': 255.0, 'y': 166.0}
      location_once_scrolled_into_view 可见不可见都会滚动到顶部对齐,('y'依旧是166.0
        结果也是相对frame即当前相应html的坐标{'x': 255.0, 'y': 166.0}
# 总结
location
  始终不滚动,返回相对整个html或者对应frame的坐标
location_once_scrolled_into_view
  chrome完全可见不滚动,firefox始终会滚动;而且chrome底部元素会底部对齐,其余情况两者都是顶部对齐。
  一般返回相对可视区域坐标,但是firefox的frame依旧返回相对frame的坐标
# 摘自:https://zhuanlan.zhihu.com/p/25171554
selenium.webdriver 内置了截取当前页面的功能,其中:
  a.webdriver.chrome自带的方法只能对当前窗口截屏,若是需要截取的窗口超过了一屏,就只能另辟蹊径了。
  b.webdriver.phantomjs自带的方法支持对整个网页截屏。

总结

以上所述是小编给大家介绍的selenium+python实现1688网站验证码图片的截取功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://blog.csdn.net/zwq912318834/article/details/78605486

延伸 · 阅读

精彩推荐