(selenium测试常用代码)老年人自用
加入头
from selenium import webdriver # 打开网页创建对象
from selenium.webdriver.common.by import By #Xpath的寻找
from selenium.webdriver.support.ui import WebDriverWait #隐性等待
from selenium.webdriver.support import expected_conditions as EC #隐性等待
python中urllib.parse有三个方法:quote, unquote, urlencode
from urllib.parse import quote,unquote
unquote负责解码
读取Excel,将其转换为字典
df = pd.read_excel(excel_file_path)
# 获取所有行
all_rows = df
if not all_rows.empty:
# 将每一行的信号名和数据存储为字典列表
dict_data = {}
for i, row in all_rows.iterrows():
# 遍历每一行的列(信号),将信号名和对应数据存储为字典
row_data = {signal: str(row[signal]) for signal in df.columns}
dict_data[i] = row_data
num_rows =all_rows.shape[0]
return dict_data,num_rows
else:
print("未找到任何行。")
return None
谷歌浏览器设置
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches",["enable-logging"])#启动排除日志详细内容,使log更加清楚
options.add_experimental_option("detach", True)#不自动关闭浏览器
options.add_argument('ignore-certificate-errors')#忽略SSL证书错误
options.add_experimental_option("prefs", {
"download.default_directory": self.download_folder,
"download.prompt_for_download": False, # 禁用下载前的弹窗询问
"download.directory_upgrade": True,
"safebrowsing.enabled": True
})
os.makedirs(self.download_folder, exist_ok=True)
简单的使用selenium
def test(self):
self.driver.get(now_url)
self.driver.maximize_window()
element = WebDriverWait(self.driver, 20).until(
EC.visibility_of_element_located((By.XPATH, xpath_user)))
element.send_keys(self.user)
self.driver.find_element(By.XPATH,xpath_psword).send_keys(self.psword)
self.driver.find_element(By.XPATH,xpath_signin).click()
time.sleep(5)
self.driver.get(now_url)
WebDriverWait(self.driver, 10).until(
EC.visibility_of_element_located((By.XPATH, '//*[@id="fr-btn-FORMSUBMIT0"]/div/em/button'))
).click()
在一个文件夹中等待最新的文件下载完成
while not file_path:
files = os.listdir(self.download_folder)
files.sort(key=lambda x: os.path.getmtime(os.path.join(self.download_folder, x)), reverse=True) # 按照修改时间降序排序
newest_file = files[0] if files else None
count = 0
if newest_file.endswith(".xlsx") and not newest_file.endswith(".crdownload"):
print("正在寻找最新的xlsx文件")
if newest_file and time.time() - os.path.getmtime(
os.path.join(self.download_folder, newest_file)) < 30: # 判断文件是否是最近30秒内修改的
print("找到最新的xlsx了:", newest_file)
file_path = os.path.join(self.download_folder, newest_file)
print(file_path)
break
else:
time.sleep(5)
else:
time.sleep(1)
count +=1
if count ==15:
break
return file_path
最后数据对比
def datamatch(self,data_dict):
match_res = 0
error_dic = {}
print(1)
for Parm in self.para_dict.keys():
if Parm in data_dict.keys():
if self.para_dict[Parm] == data_dict[Parm]:
print(21)
print('******匹配成功******')
# _INResultState_.setResult("Passed")
temp = f'******匹配成功******:{Parm}的查询值为{data_dict[Parm]},期望值为{self.para_dict[Parm]}******'
# addText(temp)
print(temp)
else:
print('******匹配失败:%s的查询值为%s,期望值为%s******' % (Parm, data_dict[Parm], self.para_dict[Parm]))
# _INResultState_.setResult("Failed")
match_res += 1
print(22)
# error_dic[Parm] = [baseInfo[Parm], parm_dic[Parm]]
temp = f'******匹配失败:{Parm}的查询值为{data_dict[Parm]},期望值为{self.para_dict[Parm]}******'
print(temp)
# addText(temp)
else:
# _INResultState_.setResult("Failed")
print("******匹配错误:没有查找到参数名******")
# error_dic[Parm] = ['NO This Parm']
temp = f'******匹配错误:没有查找到参数名{Parm}******'
print(temp)
match_res += 1
当你需要进阶使用selenium的时候,你需要使用selenium-wire包,使用该包可以在网页的基础上,进行request,请求post内容
for request in driver.requests:
if request.url == "https://zapi.z-onesoftware.cn/ba/cvl/shadow/getEntireCarInfo" and request.method == "POST":
#https://zapi-es33.z-onesoft.cn/ba/cvl/shadow/getEntireCarInfo
# print("Url:", request.url)
# print("Code:", request.response.status_code)
# print("method", request.headers)
# print("Response:", request.response.headers)
# print("Response:", request.response.body)
try:
data_cloud = request.response.body
data_cloud = BytesIO(data_cloud)
data_cloud = gzip.GzipFile(fileobj=data_cloud)
data_cloud = data_cloud.read().decode("UTF-8")
data_cloud = json.loads(data_cloud)["data"]
print(data_cloud)
# data_cloud = json.loads(request.response.body.decode("utf-8"))["data"]
# print(data_cloud)
for key, value in data_cloud.items():
if type(value) == dict:
for k, v in data_cloud[key].items():
new_data_cloud[k] = v
continue
new_data_cloud[key] = value
log("云端数据获取完成")
except:
log("云端数据不存在")
break