安装selenium包
pycharm - terminal - 执行 pip install selenium

问题:

pip版本过低
执行 python -m pip install --ugrade pip 升级pip版本
重新执行pip install selenium
升级失败。
pycharm - file -settings - project - project interpreter

点击最右边+安装

搜索-选中-点击install papackage

下载chrome driver
chrome driver和浏览器版本要一一对应
查看chrom浏览器版本
三个点-帮助-关于

找到chrome版本

下载对应的chrome driver
百度搜索chrome driver

随便选择一个版本

点击notes.txt

查看chromedriver是否可用

下载chrome driver

把chromedriver.exe添加到工程里
解压压缩包

工程中新建一个文件夹

复制chromedriver.exe到文件夹中

打开浏览器
#确定chromedriver.exe的位置
driver_path = os.path.join(os.path.dirname(__file__),"../../chromedriver/chromedriver.exe")
# 打开浏览器
driver = webdriver.Chrome(driver_path)
driver.maximize_window() # 最大化浏览器
driver.set_page_load_timeout(10)#网页加载超时为10s
driver.set_script_timeout(10)#js脚本运行超时10s
driver.implicitly_wait(10)#元素查找超时时间10s

打开网址
driver.get("https://www.baidu.com")
退出浏览器
driver.quit()
通过xpath定位元素
username = driver.find_element_by_xpath("//input[@name='username']")
元素操作
文本输入框
#清空
username.clear()
#填值
username.send_keys("admin")
按钮
login.click()
窗口切换
iframe
切换到iframe
#定位iframe
iframe = driver.find_element_by_xpath("(//iframe[contains(@id,'vue-tinymce-')])[1]")
#切换到上边定位到的iframe
driver.switch_to.frame(iframe)
切出iframe
#切出iframe
driver.switch_to.default_content()
浏览器导航栏操作
鼠标键盘操作
其他操作
获取页面源代码
driver.page_source
下拉滚动条
js = "var q=document.documentElement.scrollTop=10000"
driver.execute_script(js)
使用pytest.fixture控制测试流程
项目中新建一个名字为conftest.py的文件
- session 所有用例执行之前执行
- module 每个脚本文件执行之前执行
- class 每个class执行之前执行
- function 每个测试方法执行之前执行
@pytest.fixture(scope="session")
def driver():
driver_path = os.path.join(os.path.dirname(__file__), "../chromedriver/chromedriver.exe")
# 打开浏览器
dr = webdriver.Chrome(driver_path)
dr.maximize_window() # 最大化浏览器
dr.set_page_load_timeout(10)#网页加载超时为10s
dr.set_script_timeout(10)#js脚本运行超时10s
dr.implicitly_wait(10)#元素查找超时时间10s
yield dr
dr.quit()
网友评论