selenium自动化测试+获取验证码图片

所谓自动化测试,就是通过电脑模拟人为的输入测试。

Selenium  是一个用于Web应用程序测试的工具,测试直接运行在浏览器中,就像真正的用户在操作一样。Selenium 的核心,也称browser bot,是用 JavaScript 编写的,这使得测试脚本可以在受支持的浏览器中运行。但是每个浏览器访问方式是不一样的,所以需要安装对应浏览器的webdriver,才能在相应的浏览器上进行测试。

python+selenium的组合方式,会极大的减轻人工输入的工作量。本人目前是采用的win7+python3.7的环境。下面讲一下怎么使用selenium。

1,安装selenium,直接通过命令:

pip install -U selenium

2,添加浏览器驱动webdriver支持

由于本人采用的chrome46,所以下载的webdriver要与相应webdriver支持的版本对应,怎么知道webdriver支持的chrome版本,请看:

https://sites.google.com/a/chromium.org/chromedriver/downloads

然后根据当前chrome版本,选择合适的webdriver:

https://chromedriver.storage.googleapis.com/index.html

然后将解压后的exe文件(chromedriver.exe)放在python安装目录,即python.exe同一目录下。使用其它浏览器时,需要下载其它浏览器对应的webdriver。

3,测试代码

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")
driver.find_element_by_id("kw").send_keys("selenium")

上面的代码将打开chrome浏览器,并在搜索文本框中输入selenium。

4,获取验证码图片

获取验证码图片时,不能通过下面这种方式获取:

r = requests.get(url, stream=True, timeout=60)
        r.raise_for_status()
        with open(filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=1024):
                if chunk:  # filter out keep-alive new chunks
                    f.write(chunk)
                    f.flush()

这种方式会重新发送请求来获取图片,但是重新请求后验证码肯定会改变,所以我们只能通过截屏的方式来获取验证码。

# encoding:utf-8
from PIL import Image
from selenium import webdriver
import time

url = 'http://www.scliangfu.com/Themes/Manages/Login.aspx'
driver = webdriver.Chrome()
driver.maximize_window()  # 将浏览器最大化
driver.get(url)
# 截取当前网页并放到E盘下命名为printscreen,该网页有我们需要的验证码
time.sleep(1)
driver.save_screenshot('E:\\printscreen.png') 

imgelement = driver.find_element_by_xpath('//*[@id="Image1"]')  # 定位验证码
location = imgelement.location  # 获取验证码x,y轴坐标
size = imgelement.size  # 获取验证码的长宽
rangle = (int(location['x']), int(location['y']), int(location['x'] + size['width']),
          int(location['y'] + size['height']))  # 写成我们需要截取的位置坐标
i = Image.open("E:\\printscreen.png")  # 打开截图
frame4 = i.crop(rangle)  # 使用Image的crop函数,从截图中再次截取我们需要的区域
frame4.save('E:\\save.jpg') # 保存我们接下来的验证码图片 进行打码


driver.close()

上面的代码可以直接运行,将验证码(id="Image1")的图片截屏裁剪出来。

 

转载于:https://my.oschina.net/moluyingxing/blog/2997353

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值