测试人论坛搜索功能实战
- 添加了截图
- 添加了获取前端代码
- 添加了显式等待与隐式等待
- 添加了断言
import pytest
import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
'''
获取chromedriver地址
https://npm.taobao.org/mirrors/chromedriver/
https://googlechromelabs.github.io/chrome-for-testing/
http://chromedriver.storage.googleapis.com/index.html
chromedriver --version
作业:
打开测试人论坛,截图。
跳转到高级搜索页面,添加显式等待判断页面跳转成功并截图。
搜索输入框输入搜索关键字,截图。关键字清单如下:
Selenium
Appium
面试
打印当前结果页面的pagesource并截图。
打印搜索结果的第一个标题。
断言:第一个标题是否包含关键字。
'''
class TestDemo01():
def setup_method(self, method):
# 实例化chromedriver
self.driver = webdriver.Chrome()
# 添加全局隐式等待
self.driver.implicitly_wait(5)
def teardown_method(self, method):
# 关闭driver
self.driver.quit()
@pytest.mark.parametrize("case,asserts",[('python', 'python'), ('Appium', 'Appium'), ('面试', '面试')])
def test_demo01(self,case,asserts):
# 访问网站
self.driver.get("https://ceshiren.com/search?expanded=true")
#自定义显示等待,按照次数轮查
def click_execption(by,element,atrempts=5):
def __inner(driver):
'''
多次点击同个按钮
'''
count = 0 #实际循环次数
while count < atrempts:
try:
count +=1
driver.find_element(by,element).click()
return True
except Exception:
print('出现异常啦')
return False
return __inner
#自定义显示等待,按照次数轮查
def text_execption(by,element,atrempts=5):
def __inner(driver):
'''
多次点击同个按钮
'''
count = 0 #实际循环次数
while count < atrempts:
try:
count +=1
text = driver.find_element(by,element).text
return text
except Exception:
print('出现异常啦')
return False
return __inner
# 输入 搜索内容
self.driver.find_element(By.ID, "ember15").send_keys(case)
# 显示等待 点击搜索
WebDriverWait(self.driver,10).until(click_execption(By.XPATH, '//*[@id="ember13"]/div[2]/div[1]/button'))
# 显示等待 获取文字
rep_text = WebDriverWait(self.driver,10).until(text_execption(By.XPATH, '//*[@id="search-result-count"]'))
print(rep_text)
# 获取网页代码
with open(f'./images/{case}.html','w',encoding='u8') as f:
f.write(self.driver.page_source)
# 截图
self.driver.save_screenshot(f'./images/{case}.png')
assert asserts in rep_text