selenium Python截取图片二维码

from selenium import webdriver
import time
from PIL import Image, ImageEnhance
from chaojiying import Chaojiying_Client
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import sys
from selenium.webdriver import Chrome
import os
import logging
 
driver = webdriver.Chrome()
driver.maximize_window()  # 最大化窗口
driver.get("https://www.网址.com/")
driver.implicitly_wait(10)  # 隐式等待,设置等待时长10秒
dir = os.getcwd()# 获取当前文件目录
dirPath1 = os.path.join(dir,'全屏截图.png')#保存在文件运行目录
dirPath2 = os.path.join(dir,r'C:\Users\Administrator\二维码截图.png')#保存在指定目录

def screenshot(driver):
    driver.refresh()
    time.sleep(5)
    driver.save_screenshot(dirPath1)  # 截取全屏图片,保存到本地
    js = 'var action=document.documentElement.scrollTop=200'  
    # 设置滚动条距离顶部的位置,设置为 200, 超过10000就是最底部。一屏展示不全时需要滚屏
    time.sleep(2)#滚屏后等待,防止未加载完成定位偏差
    driver.execute_script(js)
    location = driver.find_element_by_id("verifyimg").location
    size = driver.find_element_by_id("verifyimg").size
    left = location['x']
    top = location['y']
    right = location['x'] + size['width']
    bottom = location['y'] + size['height']
    ran = Image.open(dirPath1)  # 打开截图,获取验证码位置,截取保存验证码
    box = (left, top, right, bottom)  # 获取验证码位置,代表(左,上,右,下)
    ran.crop(box).save(dirPath2)  # 把获取的验证码保存  crop裁剪函数
    chaojiying = Chaojiying_Client('账号', '密码', '907698')  
    # 用户中心>>软件ID 生成一个替换 907698
    im = open(dirPath2, 'rb').read()
    png = chaojiying.PostPic(im, 1004)
    print(png)
    code = png['pic_str']
    wrong1 = png['pic_id']
    print("图片识别码: " + wrong1)
    print("验证码是:" + str(code))
    new_time = time.strftime('%m%d%H%M%S', time.localtime())  # 获取当前时间
    print("当前时间为:" + new_time)
    
    if is_element_exist(driver, "//p[@class='form-ajaxtip']"):
        print("调用一次报错接口")
        chaojiying.ReportError(wrong1)

    return name

def is_element_exist(driver, xpath1):
    try:
        driver.find_element_by_xpath(xpath1)
        return 0
    except:
        return 1

res = 1
n = 0
while res:
    name = screenshot(driver)
    res = is_element_exist(driver, "/html/body/div[3]/div/div/div[3]/a[1]")
    n += 1
    print("尝试次数n = " + str(n))
    if n > 2:
        sys.exit()#终止本次运行,不在控制台报错
···
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容