开头
用配置好的 selenium 进行一个简单的测试用例的编写,可以参考allure的美化这一遍博文 https://www.cnblogs.com/c-keke/p/14837766.html
代码编写
新建一个测试用例test_02.py, 开启一个远程selenium调试,编写如下代码
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File :test_02.py
@Describe :
@Create :2021/06/23 00:16:26
@Author :od
'''
import pytest
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
class Testerhome:
def setup(self):
self.chrome_options = Options()
self.chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") # 指定配置好的 chrom
self.chrome_driver = r"./chromedriver.exe" # 驱动路径
self.driver = webdriver.Chrome(self.chrome_driver, chrome_options=self.chrome_options) # 加入驱动设置
self.driver.get('https://testerhome.com/') # 发起请求
self.driver.implicitly_wait(3) # 添加一个隐式等待默认等待3秒
def teardown(self):
print('关闭浏览器')
time.sleep(1)
# self.driver.quit()
# 测试用例如果不加sleep的话,元素如果没加载出来,是会报错的,所以我们要加个隐式等待
def test_hogwards(self):
self.driver.find_element_by_xpath("//a[contains(text(),'社团')]").click() # 点击涉毒案
self.driver.find_element_by_xpath("//a[contains(text(),'求职面试圈')]").click() # 选择一个活跃的社团
self.driver.find_element_by_xpath("//a[@title='面试瓶颈']").click() # 点击一个帖子
print('go')
执行: pytest -vs test_02 即可得到结果
显示等待和隐式等待得区别
隐式等待: 设置一个等待时间,轮询查找(默认0.5秒)元素是否出现,如果没有出现,就会抛错,是个全局得等待
self.driver.implicitly_wait(3)
显示等待: 在代码中定义等待条件,当条件发生时才继续执行代码
webDriverwait 配合 until() 和 until_not 方法,根据判断条件进行等待
from selenium.webdriver.support.wait import WebDriverWait
def wail(x): # x虽然没用到,但是是一定要传得
return len(self.driver.find_elements(By.XPATH, "//a[contains(text(),'求职面试圈')]")) >= 1
WebDriverWait(self.driver, 10).until(wail) # until里面需要提供一个函数,wait不能加括号,如果写了括号,代表的是调用,只能不写括号传进来
self.driver.find_element_by_xpath("//a[@title='面试瓶颈']").click() # 点击一个帖子
或者
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
WebDriverWait(self.driver, 10).until(expected_conditions.element_to_be_clickable((By.Xpath, "//a[contains(text(),'求职面试圈')]")))
完。