溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

selenium+python如何實(shí)現(xiàn)688網(wǎng)站驗(yàn)證碼圖片的截取功能

發(fā)布時(shí)間:2021-04-13 10:04:21 來源:億速云 閱讀:388 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下selenium+python如何實(shí)現(xiàn)688網(wǎng)站驗(yàn)證碼圖片的截取功能,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

1. 背景

?在1688網(wǎng)站爬取數(shù)據(jù)時(shí),如果訪問過于頻繁,無論用戶是否已經(jīng)登錄,就會(huì)彈出如下所示的驗(yàn)證碼登錄框。

selenium+python如何實(shí)現(xiàn)688網(wǎng)站驗(yàn)證碼圖片的截取功能

一般的驗(yàn)證碼是類似于如下的元素(通過鏈接單獨(dú)加載進(jìn)頁面,而不是嵌入圖片元素):

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

?一般來說,獲取驗(yàn)證碼圖片有兩種方式:

?第一,拿到上面驗(yàn)證碼的圖片鏈接:src=”//pin.aliyun.com/get_img?identity=sm-searchweb2&sessionid=9c3a51d81de07ddf1bfd9bbc70863b0f&type=default&t=1511315617645”,但是這種方式有時(shí)候行不通。因?yàn)橛袝r(shí)候會(huì)發(fā)現(xiàn)當(dāng)前的驗(yàn)證碼和通過提取出來的url鏈接打開的驗(yàn)證碼,內(nèi)容是不一樣的,其內(nèi)容不斷發(fā)生變化。

?第二,利用selenium先進(jìn)行可視區(qū)域的截屏,然后定位驗(yàn)證碼元素的位置以及大小,然后利用Image(PIL模塊中)進(jìn)行裁剪,得到驗(yàn)證碼圖片,然后送往驗(yàn)證碼模塊或者打碼平臺(tái)處理。

2. 環(huán)境

?python 3.6.1
?系統(tǒng):win7
?IDE:pycharm
?安裝過chrome瀏覽器
?配置好chromedriver
?selenium 3.7.0

3. 分析網(wǎng)頁結(jié)構(gòu)

selenium+python如何實(shí)現(xiàn)688網(wǎng)站驗(yàn)證碼圖片的截取功能

通過分析網(wǎng)頁源代碼,我們可以得出以下結(jié)論:

?這個(gè)驗(yàn)證碼登錄框是通過iframe嵌入到網(wǎng)頁中的。
?頁面中不止這一個(gè)iframe嵌套。
?這個(gè)驗(yàn)證碼iframe有很明顯的特征:id=”sufei-dialog-content”和src=”https://sec.1688.com/query.htm?……”

<iframe id="sufei-dialog-content" frameborder="none" src="https://sec.1688.com/query.htm?style=mini&amp;smApp=searchweb2&amp;smPolicy=searchweb2-RpcAsyncAll-anti_Spider-checkcode&amp;smCharset=GBK&amp;smTag=MTIxLjE1LjI2LjIzMywzNTE1MTA4MjI5LGFlNGE1ZGI1YTQ4NDQ3NTNiYzY5OTZlZmU1OWE3Njhm&amp;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&amp;smSign=XKm5xSgAkIixvOkhV1VSyg%3D%3D" cd_frame_id_="c4ae94ef2bea60f0b4729f319df59251"></iframe>

4. 代碼

# 前提是,在程序啟動(dòng)時(shí),對(duì)瀏覽器窗口大小進(jìn)行了設(shè)置
from selenium import webdriver
import time
from PIL import Image
browser = webdriver.Chrome()
# 根據(jù)桌面分辨率來定,主要是為了抓到驗(yàn)證碼的截屏,驗(yàn)證碼需要出現(xiàn)在可視區(qū)域中
browser.set_window_size(960, 960)
# 處理驗(yàn)證碼彈窗
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}")
    # 找到驗(yàn)證碼登錄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']
        # 代表驗(yàn)證碼區(qū)域可見
        # 某些情況下,會(huì)出現(xiàn)驗(yàn)證碼框不彈出,而iframe還在的暫態(tài)
        if frameWidth > 0 and frameHeight > 0:
          print(f"驗(yàn)證碼彈出, 進(jìn)行處理, frameWidth = {frameWidth}, frameHeight = {frameHeight}")
          # 截屏,在chrome中截取的是可視區(qū)域,而不是整個(gè)html頁面
          # 前提是當(dāng)前project下已經(jīng)創(chuàng)建了clawerImgs目錄
          browser.get_screenshot_as_file('clawerImgs/screenshot.png')
          # 先拿到iframe在整個(gè)可視頁面(也就是上面的截屏)中的相對(duì)位置,因?yàn)榍懊鎸?duì)頁面的窗口大小進(jìn)行了設(shè)置960 X 960
          # location_once_scrolled_into_view 拿到的是相對(duì)于可視區(qū)域的坐標(biāo)
          # location 拿到的是相對(duì)整個(gè)html頁面的坐標(biāo)
          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的圖片 ———— 無意義,只是做經(jīng)驗(yàn)總結(jié)
          imgFrame = Image.open('clawerImgs/screenshot.png')
          imgFrame = imgFrame.crop((left, top, right, bottom)) # 裁剪
          imgFrame.save('clawerImgs/iframe.png')
          # 切換到驗(yàn)證碼彈出框的frame,不然無法獲取到驗(yàn)證碼元素,因?yàn)轵?yàn)證碼元素是在iframe中
          browser.switch_to.frame(iframe)
          # ------獲取驗(yàn)證碼圖片,第一種方法:在frame區(qū)域截取
          # 獲取指定元素位置
          captchaElem = browser.find_element_by_xpath("//img[contains(@id, 'CheckCodeImg')]")
          # 因?yàn)轵?yàn)證碼在frame中沒有縮放,直接取驗(yàn)證碼圖片的絕對(duì)坐標(biāo)
          # 這個(gè)坐標(biāo)是相對(duì)于它所屬的frame的,而不是整個(gè)可視區(qū)域
          captchaX = int(captchaElem.location['x'])
          captchaY = int(captchaElem.location['y'])
          # 取驗(yàn)證碼的寬度和高度
          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區(qū)域截取
          imgObject = Image.open('clawerImgs/iframe.png')
          imgCaptcha = imgObject.crop((captchaX, captchaY, captchaRight, captchaBottom))   # 裁剪
          imgCaptcha.save('clawerImgs/captcha1.png')
          # ------獲取驗(yàn)證碼圖片,第二種方法:在整個(gè)可視區(qū)域截取。 就要加上這個(gè)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處理圖像,第二種方法:在整個(gè)可視區(qū)域截取
          imgObject = Image.open('clawerImgs/screenshot.png')
          imgCaptcha = imgObject.crop((captchaX, captchaY, captchaRight, captchaBottom))    # 裁剪
          imgCaptcha.save('clawerImgs/captcha2.png')

5. 結(jié)果展示

?整個(gè)可視區(qū)域:screenshot.png

selenium+python如何實(shí)現(xiàn)688網(wǎng)站驗(yàn)證碼圖片的截取功能

?驗(yàn)證碼登錄框iframe區(qū)域:iframe.png

selenium+python如何實(shí)現(xiàn)688網(wǎng)站驗(yàn)證碼圖片的截取功能

?相對(duì)于iframe截取的驗(yàn)證碼圖片:captcha1.png

selenium+python如何實(shí)現(xiàn)688網(wǎng)站驗(yàn)證碼圖片的截取功能

?相對(duì)于整個(gè)可視區(qū)域截取的驗(yàn)證碼圖片:captcha2.png

selenium+python如何實(shí)現(xiàn)688網(wǎng)站驗(yàn)證碼圖片的截取功能

6. 拓展

# 摘自https://www.cnblogs.com/my8100/p/7225408.html
chrome
  default:
    location 不滾動(dòng),直接返回相對(duì)整個(gè)html的坐標(biāo) {'x': 15.0, 'y': 129.0}
    location_once_scrolled_into_view 返回相對(duì)可視區(qū)域的坐標(biāo)(改變?yōu)g覽器高度,可以觀察到底部元素底部對(duì)齊后y的變化)
      頂部/底部元素 完全可見不滾動(dòng),{u'x': 15, u'y': 60}
      頂部元素部分可見或完全不可見都會(huì)滾動(dòng)到 頂部對(duì)齊 {u'x': 15, u'y': 0} account-wall
      底部元素部分可見或完全不可見都會(huì)滾動(dòng)到 底部對(duì)齊 {u'x': 15, u'y': 594} theme-list
  frame:
    location 不滾動(dòng),直接返回相對(duì)frame即當(dāng)前相應(yīng)內(nèi)層html的坐標(biāo){'x': 255.0, 'y': 167.0} captcha_frame 的 lc-refresh
    location_once_scrolled_into_view 返回相對(duì)可視區(qū)域的坐標(biāo)
      完全可見不滾動(dòng){u'x': 273, u'y': 105}
      部分可見或完全不可見滾動(dòng)到 頂部對(duì)齊 {u'x': 273, u'y': 0}
  firefox
    default:
      頂部元素 底部元素
        location 不滾動(dòng),直接返回相對(duì)整個(gè)html的坐標(biāo) {'x': 15.0, 'y': 130.0} {'x': 15.0, 'y': 707.0}
        location_once_scrolled_into_view 返回相對(duì)可視區(qū)域的坐標(biāo)(y=1足以說明)
          可見不可見 都滾動(dòng)到頂部對(duì)齊 {'x': 15.0, 'y': 1.0} {'x': 15.0, 'y': 1.0}
          如果下拉條直到底部,底部元素仍然無法頂部對(duì)齊 {'x': 15.0, 'y': 82.0}
    frame:
      location 不滾動(dòng),都是相對(duì)frame即當(dāng)前相應(yīng)html的坐標(biāo){'x': 255.0, 'y': 166.0}
      location_once_scrolled_into_view 可見不可見都會(huì)滾動(dòng)到頂部對(duì)齊,('y'依舊是166.0)
        結(jié)果也是相對(duì)frame即當(dāng)前相應(yīng)html的坐標(biāo){'x': 255.0, 'y': 166.0}
# 總結(jié)
location 
  始終不滾動(dòng),返回相對(duì)整個(gè)html或者對(duì)應(yīng)frame的坐標(biāo)
location_once_scrolled_into_view
  chrome完全可見不滾動(dòng),firefox始終會(huì)滾動(dòng);而且chrome底部元素會(huì)底部對(duì)齊,其余情況兩者都是頂部對(duì)齊。
  一般返回相對(duì)可視區(qū)域坐標(biāo),但是firefox的frame依舊返回相對(duì)frame的坐標(biāo)
# 摘自:https://zhuanlan.zhihu.com/p/25171554
selenium.webdriver 內(nèi)置了截取當(dāng)前頁面的功能,其中:
  a.WebDriver.Chrome自帶的方法只能對(duì)當(dāng)前窗口截屏,若是需要截取的窗口超過了一屏,就只能另辟蹊徑了。
  b.WebDriver.PhantomJS自帶的方法支持對(duì)整個(gè)網(wǎng)頁截屏。

以上是“selenium+python如何實(shí)現(xiàn)688網(wǎng)站驗(yàn)證碼圖片的截取功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI