使用selenium写一些公共类有一些方法验证元素比如判断文本框是否存在若存在输入数据有多个文本框输入或者单个文本框输入判断点击按钮是否存在若存在点击按钮点击按钮之后根据元素查找对用的列是否有数据有数据就记录判断连接能否点击可点击就下载点击下载判断下载是否完成没有完成记录下载失败的文件并重试3次记录重试下载失败的文件且需要记录如果其中的某一步验证失败都需要记录失败的记录精确到那一步错误并结束程序运
下面是使用Selenium编写的一个公共类示例,其中包含了上述提到的几个方法。请注意,这只是一个示例,你可能需要根据你的具体需求进行修改和扩展。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class CommonMethods:
def __init__(self):
self.driver = None
def open_browser(self):
self.driver = webdriver.Chrome() # 选择适合你的浏览器驱动
def close_browser(self):
if self.driver:
self.driver.quit()
def find_element(self, locator):
try:
element = WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located(locator)
)
return element
except:
self.record_failure("找不到元素: " + str(locator))
return None
def input_text(self, locator, text):
element = self.find_element(locator)
if element:
element.send_keys(text)
def click_button(self, locator):
element = self.find_element(locator)
if element:
element.click()
def is_element_visible(self, locator):
element = self.find_element(locator)
if element:
return element.is_displayed()
return False
def is_link_clickable(self, locator):
element = self.find_element(locator)
if element:
return element.is_enabled()
return False
def download_file(self, locator):
if self.is_link_clickable(locator):
element = self.find_element(locator)
element.click()
# 等待下载完成的逻辑,根据具体情况实现
def record_failure(self, message):
# 将错误信息记录到日志或其他地方
print("失败记录: " + message)
# 结束程序运行的逻辑,根据具体情况实现
你可以在你的测试脚本中使用这个公共类来执行你的测试操作。例如:
common_methods = CommonMethods()
common_methods.open_browser()
# 判断文本框是否存在,若存在,输入数据
if common_methods.is_element_visible((By.ID, "textbox1")):
common_methods.input_text((By.ID, "textbox1"), "Some text")
# 判断点击按钮是否存在,若存在,点击按钮
if common_methods.is_element_visible((By.ID, "button1")):
common_methods.click_button((By.ID, "button1"))
# 点击按钮之后,根据元素查找对应的列是否有数据,有数据就记录
if common_methods.is_element_visible((By.XPATH, "//td[@class='data-column']")):
data_elements = common_methods.driver.find_elements(By.XPATH, "//td[@class='data-column']")
data_list = [element.text for element in data_elements]
# 记录数据
# 判断连接能否点击,可点击就下载
if common_methods.is_link_clickable((By.ID, "download_link")):
common_methods.download_file((By.ID, "download_link"))
common_methods.close_browser()
请注意,这个示例只是一个基本的框架,你需要根据你的具体需求和网站的结构进行适当的修改和扩展。例如,你可能需要使用不同的定位策略(如CSS选择器)或等待条件来查找和操作元素。同时,你可能需要添加错误处理机制来处理特殊情况,如下载失败和重试等
原文地址: https://www.cveoy.top/t/topic/it2A 著作权归作者所有。请勿转载和采集!