Selenium 自动化测试(二)
自动化测试工具环境搭建
下载安装 Python
https://www.python.org
安装版本3.7.6. [https://www.python.org/downloads/release/python-376/]
添加至文件夹Scripts路径至系统环境变量Path里:
安装 Selenium
pip install selenium
pip list
Package Version
----------------- ---------
async-generator 1.10
attrs 22.2.0
certifi 2022.12.7
cffi 1.15.1
exceptiongroup 1.1.1
h11 0.14.0
idna 3.4
outcome 1.2.0
pip 19.2.3
pycparser 2.21
PySocks 1.7.1
selenium 4.8.2
setuptools 41.2.0
sniffio 1.3.0
sortedcontainers 2.4.0
trio 0.22.0
trio-websocket 0.10.2
typing-extensions 4.5.0
urllib3 1.26.15
wsproto 1.2.0
WARNING: You are using pip version 19.2.3, however version 23.0.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
下载安装 PyCharm
https://www.jetbrains.com/pycharm/
下载安装社区版:
https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows&code=PCC
安装完成后新建一个项目,需要指定Interpreter:
执行Main,查看运行结果正常:
下载安装浏览器驱动 Web driver
- 查看浏览器版本:帮助 > 关于
- 下载对应版本驱动
Chrome: https://chromedriver.chromium.org/downloads
Edge: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/ - 将driver放到一个folder中,并将此folder路径加入系统环境变量
第一个 case
打开Chrome,访问百度,输入“Selenium”搜索,关闭退出浏览器。
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
driver = webdriver.Chrome()
driver.get('http://www.baidu.com')
sleep(3)
driver.find_element(By.ID, 'kw').send_keys('selenium')
sleep(3)
driver.find_element(By.ID, 'su').click()
sleep(3)
driver.quit()
重构 test case:
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
class TestCase(object):
def __init__(self):
self.driver = webdriver.Chrome()
def test(self):
self.driver.get('http://www.baidu.com')
sleep(3)
self.driver.find_element(By.ID, 'kw').send_keys('selenium')
sleep(3)
self.driver.find_element(By.ID, 'su').click()
sleep(3)
self.driver.quit()
if __name__ == '__main__':
case = TestCase()
case.test()
Selenium元素定位
新版的Python使用find_elements(by=By.CLASS_NAME, value=name) 形式,借助 By 来传入定位方式,需要先引入,主要是为了防止定位方式写错。
By.ID
driver.find_element(By.ID, 'kw').send_keys('selenium')
By.NAME
driver.find_element(By.NAME, 'wd').send_keys('selenium')
By.CLASS_NAME
driver.find_element(By.CLASS_NAME, 's_ipt').send_keys('selenium')
By.TAG_NAME
By.LINK_TEXT
By.PARTIAL_LINK_TEXT
By.CSS_SELECTOR
driver.find_element(By.CSS_SELECTOR, “#kw”).send_keys(“A”)
By.XPATH
xpath xml path 根据xml的路径进行定位
- xml x:可扩展的 m:标记 l:语言
- html h:超 t:文本 标记语言 (超出文本范畴)只能运用有限的几种标签,所以html是不可扩展的
XML和HTML一样是标签语言,通过标签的嵌套来表达信息。xml自然而然形成了父节点、子节点、后代节点、相先节点、同胞节点等关系。而xpath就是用来在这些节点中找到所需要的.
driver.find_element(By.XPATH, "//*[@id='kw']").send_keys("A")
driver.find_element(By.XPATH, "/html/body/div[1]/div[1]/div[5]/div/div/form/span[1]/input").click() #full path