Python_Xpath应用_数据驱动
Xpath应用_数据驱动
一、示例:访问不同的网页
数据文件urls.txt内容
http://www.baidu.com http://www.sogou.com http://www.bing.com
程序文件内容
#encoding:utf-8 from selenium import webdriver import time driver=webdriver.Firefox(executable_path = "D:\\geckodriver.exe") driver.get("http://www.sogou.com") search_box = driver.find_element_by_xpath("//input[@id='query']") search_box.send_keys("光荣之路测试开发") query_button = driver.find_element_by_xpath("//input[@id='stb']") query_button.click() time.sleep(5) assert "光荣之路" in driver.page_source #断言 driver.quit()
二、示例:访问bing网页、输入搜索内容并查询
数据文件内容:
https://www.baidu.com||//input[@id="kw"]||//input[@id="su"]||光荣之路测试||测试 https://www.sogou.com||//input[@id='query']||//input[@id='stb']||光荣之路测试||测试 https://www.bing.com||//input[@id="sb_form_q"]||//input[@id="sb_form_go"]||光荣之路测试||测试
程序文件内容:
from selenium import webdriver import time import os.path import sys def get_data_from_file(data_file_path,coding="utf-8"): if not os.path.exists(data_file_path): print("数据文件的路径不存在!") sys.exit(0) test_data = [] with open(data_file_path,'r',encoding=coding) as fp: for line in fp: if line.strip()=="": continue test_data.append(line.split("||")) return test_data test_data = get_data_from_file("e:\\urls.txt") #print(test_data) def test_step(url,searchbox_xpath, search_button_xpath,search_word,assert_word): driver=webdriver.Firefox(executable_path = "E:\\geckodriver") driver.get(url) search_box = driver.find_element_by_xpath(searchbox_xpath) search_box.send_keys(search_word) query_button = driver.find_element_by_xpath(search_button_xpath) query_button.click() time.sleep(5) assert assert_word in driver.page_source driver.quit() for data in test_data: url = data[0].strip() searchbox_xpath = data[1].strip() search_button_xpath = data[2].strip() search_word = data[3].strip() assert_word = data[4].strip() #print(url,searchbox_xpath, search_button_xpath,search_word,assert_word) test_step(url,searchbox_xpath, search_button_xpath,search_word,assert_