ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Web自动化第一步-登录

2022-06-13 11:33:41  阅读:151  来源: 互联网

标签:Web code 登录 第一步 driver print import div find


1.手动输入验证码:

# author:nly
# 时间:2022/6/8 15:28
# from tkinter import Image
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By
import password
# 2.导入unittest
import unittest


# 1.新建一个类,继承unittest.TestCase
class TestCase(unittest.TestCase):

    # 定义一个test开头的方法
    def test_01_login(self):
        global driver
        # 打开浏览器
        driver = webdriver.Chrome()
        # 加载网页
        driver.get("http://192.168.2.28:8087/")
        # 定位元素
        driver.find_element(By.ID, "username").send_keys("admin")
        driver.find_element(By.ID, "password").send_keys(password.PW)
        driver.save_screenshot('a.png')
        # 定位验证码
        code = driver.find_element(By.XPATH, "//form/div[1]/div[3]/div[1]/div[4]/div[2]/img")
        # 获取验证码的坐标,然后得到验证码的长和宽,那么就获取到验证码图片了。
        print(code.location)
        print(code.size)
        left = code.location['x']
        top = code.location['y']
        right = left + code.size['width']
        bottom = top + code.size['height']
        # 打开要截取的图片
        im = Image.open('a.png')
        # 截取图片
        im = im.crop((left, top, right, bottom))
        im.save('b.png')
        inputCode = input('请输入正确的验证码:')
        driver.find_element(By.ID, "inputCode").send_keys(inputCode)
        driver.find_element(By.XPATH, "//form/div[2]/div[1]/div[1]/span/button").click()

 

2.通过调用百度接口,实现自动输入验证码(识别成功率较低)

# author:nly
# 时间:2022/6/9 8:42
# author:nly

from PIL import Image, ImageEnhance
from selenium import webdriver
from selenium.webdriver.common.by import By
import password
from aip import AipOcr
import time
# from .nlp import AipNlp
# 2.导入unittest
import unittest


# 1.新建一个类,继承unittest.TestCase
class TestCase(unittest.TestCase):

    # 定义一个test开头的方法
    def test_01_login(self):
        global driver
        # 打开浏览器
        driver = webdriver.Chrome()
        # 加载网页
        driver.get("http://192.168.2.28:8087/")
        time.sleep(0.5)
        # 定位元素
        driver.find_element(By.ID, "username").send_keys("admin")
        driver.find_element(By.ID, "password").send_keys(password.PW)
        driver.save_screenshot('a.png')
        # 定位验证码
        code = driver.find_element(By.XPATH, "//form/div[1]/div[3]/div[1]/div[4]/div[2]/img")
        # 获取验证码的坐标,然后得到验证码的长和宽,那么就获取到验证码图片了。
        print(code.location)
        print(code.size)
        left = code.location['x']
        top = code.location['y']
        right = left + code.size['width']
        bottom = top + code.size['height']
        # 打开要截取的图片
        im = Image.open('a.png')
        # 截取图片
        im = im.crop((left, top, right, bottom))
        im.save('b.png')

        # 自动识别图片中的文字
        """我的APPID AK SK"""
        APP_ID = '百度账号分配的'
        API_KEY = '百度账号分配的'
        SECRET_KEY = '百度账号分配的'
        client = AipOcr(APP_ID, API_KEY, SECRET_KEY) # 生成一个对象

        # client.setConnectionTimeoutInMillis(2000)
        # client.setSocketTimeoutInMillis(60000)

        """读取文件,调用图片的二进制数据"""
        # 打开b.png图片,以r(read)b(bytes)方式来操作,把这个动作命名为f,读取(因为图片、视频等在电脑中以二进制来保存)
        """ 可选参数,可识别旋转的图像 """
        options = {}
        options["detect_direction"] = "true"
        # message = client.basicGeneral(img, options)  # 通用文字识别
        # message = client.basicAccurate(img, options)   # 通用文字高精度识别
        with open('b.png', 'rb') as f:
            image = f.read() # image就是这张图片的二进制内容
            time.sleep(2)
            text = client.basicAccurate(image,options)  # 调用百度帮我们生成的对象来识别图片的内容,最终获取内容,保存在text中
            res = text['words_result']
            print('res', res)
            time.sleep(2)
            data1 = ''
            for r in res:

                data1 = data1 + r['words']

            data2 = data1.replace(" ", "")

            print(data2)

        driver.find_element(By.ID, "inputCode").send_keys(data2)
        driver.find_element(By.XPATH, "//form/div[2]/div[1]/div[1]/span/button").click()

 

3.通过调用阿里接口,实现自动输入验证码(识别成功率率相对来说高一些)

# author:nly
# 时间:2022/6/9 8:42
# author:nly
import base64
from cgitb import text

import requests
from urllib import parse
from PIL import Image, ImageEnhance
from selenium import webdriver
from selenium.webdriver.common.by import By
import password
from aip import AipOcr
import time
import urllib, sys
import ssl
import json
import urllib.request
# from .nlp import AipNlp
import requests

# 2.导入unittest
import unittest


# 1.新建一个类,继承unittest.TestCase
class TestCase(unittest.TestCase):

    # 定义一个test开头的方法
    def test_01_login(self):
        global driver
        # 打开浏览器
        driver = webdriver.Chrome()
        # 加载网页
        driver.get("http://192.168.2.28:8087/")
        time.sleep(0.5)
        # 定位元素
        driver.find_element(By.ID, "username").send_keys("admin")
        driver.find_element(By.ID, "password").send_keys(password.PW)
        driver.save_screenshot('a.png')
        # 定位验证码
        code = driver.find_element(By.XPATH, "//form/div[1]/div[3]/div[1]/div[4]/div[2]/img")
        # 获取验证码的坐标,然后得到验证码的长和宽,那么就获取到验证码图片了。
        print(code.location)
        print(code.size)
        left = code.location['x']
        top = code.location['y']
        right = left + code.size['width']
        bottom = top + code.size['height']
        # 打开要截取的图片
        im = Image.open('a.png')
        # 截取图片
        im = im.crop((left, top, right, bottom))
        im.save('b.png')
        # 阿里识别图片
        host = 'http://imgurlocr.market.alicloudapi.com'
        path = '/urlimages'
        method = 'POST'
        appcode = '阿里账号分配的'  # 开通服务后 买家中心-查看AppCode
        querys = ''
        bodys = {}
        url = host + path
        image_path = r"b.png"
        with open(image_path, 'rb') as f:
             image = f.read()
             image_base64 = str(base64.b64encode(image), encoding='utf-8')
        data = {'image': 'data:image/jpeg;base64,'+image_base64+''}
        print("data:", data)
        # 或者base64
        # data = {'image':'data:image/jpeg;base64,/9j/4A......'}
        header = {"Authorization": 'APPCODE ' + appcode}
        try:
            res = requests.post(url, data, headers=header)
            res1 = res.text
            print(res1)
            resJson = json.loads(res1)
            res2 = resJson["result"][0]["words"].replace(" ", "")

        except:
            print("URL错误")
            exit()
        httpStatusCode = res.status_code

        if (httpStatusCode == 200):
            print("正常请求计费(其他均不计费)")

        else:
            httpReason = res.headers['X-Ca-Error-Message']
            if (httpStatusCode == 400 and httpReason == 'Invalid Param Location'):
                print("参数错误")
            elif (httpStatusCode == 400 and httpReason == 'Invalid AppCode'):
                print("AppCode错误")
            elif (httpStatusCode == 400 and httpReason == 'Invalid Url'):
                print("请求的 Method、Path 或者环境错误")
            elif (httpStatusCode == 403 and httpReason == 'Unauthorized'):
                print("服务未被授权(或URL和Path不正确)")
            elif (httpStatusCode == 403 and httpReason == 'Quota Exhausted'):
                print("套餐包次数用完")
            elif (httpStatusCode == 403 and httpReason == 'Api Market Subscription quota exhausted'):
                print("套餐包次数用完,请续购套餐")
            elif (httpStatusCode == 500):
                print("API网关错误")
            else:
                print("参数名错误 或 其他错误")
                print(httpStatusCode)
                print(httpReason)

        driver.find_element(By.ID, "inputCode").send_keys(res2)
        driver.find_element(By.XPATH, "//form/div[2]/div[1]/div[1]/span/button").click()

 

标签:Web,code,登录,第一步,driver,print,import,div,find
来源: https://www.cnblogs.com/niulingyu/p/16370255.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有