注册

python+selenium自动化测试(入门向干货)

今天带来的是python+selenium自动化测试的入门向教程,也是做个小总结。




我实现的大致流程为:


1 - 准备自动化测试环境

2 - 发起网页请求

3 - 定位元素

4 - 行为链



使用工具:python,selenium,chromedriver,chrom浏览器





操作步骤讲解环节




下面就是喜闻乐见的操作步骤讲解环节了(´◔౪◔)



1、准备自动化测试环境


本次的环境准备较为复杂,但是只要跟着方法走,问题应该也不是很多。

另外,软件包我都整理好了,评论区可见。



  • 准备python环境,这里网上的教程都挺多的,我也就不赘述了。
  • 导入python的第三方扩展包 - selenium,urllib3,jdcal,et_xmlfile(后三个为selenium的依赖包)
安装方法如下:
1)解压后,进入扩展包,shift+右键,在此处打开PowerShell窗口,执行命令
2)python setup.exe install
  • 安装对应版本的chrom浏览器,获取对应版本的chromedriver
这里说的对应版本,是说浏览器的版本需要与chromedriver相对应
我资源里给到的是81版本的chrom浏览器和chromedriver

2、发起网页请求

环境准备好后,就可以发起网页请求验证了。
代码如下:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# 设定目的url
url = "https://www.baidu.com/"
# 创建一个参数对象,用来控制chrome以无界面模式打开
chrome_options = Options()
# chrome_options.add_argument('--headless')
# chrome_options.add_argument('--disable-gpu')

# 跳过https安全认证页面
chrome_options.add_argument('--ignore-certificate-errors')
# 创建自己的一个浏览器对象
driver = webdriver.Chrome(chrome_options=chrome_options)
# 访问网页
driver.get(url)
# 等待防止网络不稳定引起的报错
driver.implicitly_wait(5)
# 浏览器全屏显示
driver.maximize_window()

3、定位元素

参考文档:https://python-selenium-zh.readthedocs.io/zh_CN/latest/
代码如下:

1) 根据Id定位,driver.find_element_by_id()
2) 根据 Name 定位,driver.find_element_by_name()
3) XPath定位,driver.find_element_by_xpath()
4) 用链接文本定位超链接,driver.find_element_by_link_text()
5) 标签名定位,driver.find_element_by_tag_name()
6) class定位,driver.find_element_by_class_name()
7) css选择器定位,driver.find_element_by_css_selector()

4、行为链
这里说的操作是指,定位元素后,针对元素进行的鼠标移动,鼠标点击事件,键盘输入,以及内容菜单交互等操作。
参考文档:
https://python-selenium-zh.readthedocs.io/zh_CN/latest/
https://www.cnblogs.com/GouQ/p/13093339.html
代码如下:

1) 鼠标单击事件,find_element_by_id().click()
2) 键盘输入事件,find_element_by_id().send_keys()
3) 文本清空事件,find_element_by_id().clear()
4) 右键点击事件,find_element_by_id().context_click()
5) 鼠标双击事件,find_element_by_id().double_click()


0 个评论

要回复文章请先登录注册