UI自动化入门代码
# encoding = utf-8
from selenium import webdriver
driver = webdriver.Firefox(executable_path="c://geckodriver.exe")
driver.get("http://www.baidu.com")
element = driver.find_element_by_id("kw")
element.send_keys("光荣之路")
# driver.quit()
效果:自动打开火狐浏览器,并在搜索框中输入"光荣之路"。
数据驱动
# encoding = utf-8
from selenium import webdriver
all_list = []
info_list1 = ["c://geckodriver.exe", "http://www.baidu.com", "kw", "光荣之路"]
info_list2 = ["c://geckodriver.exe", "http://www.baidu.com", "kw", "刘德华"]
info_list3 = ["c://geckodriver.exe", "http://www.baidu.com", "kw", "吴晓华"]
all_list.append(info_list1)
all_list.append(info_list2)
all_list.append(info_list3)
for info in all_list:
driver = webdriver.Firefox(executable_path=info[0])
driver.get(info[1])
element = driver.find_element_by_id(info[2])
element.send_keys(info[3])
效果:自动打开火狐浏览器,并在搜索框中输入"光荣之路"。接着代开第二个火狐浏览器窗口,并在搜索框中输入"刘德华"。接着代开第二个火狐浏览器窗口,并在搜索框中输入"吴晓华"。
继续引申为将数据存放到文件中,通过读取文件内容作为参数,来执行脚本。
# encoding = utf-8
from selenium import webdriver
with open(r"testdata.txt","r")as fp:
data = fp.readlines()
print(data)
for i in data:
print(i.split(","))
print(i.split(",")[0])
for i in data:
driver = webdriver.Firefox(executable_path=i.split(",")[0])
driver.get(i.split(",")[1])
element = driver.find_element_by_id(i.split(",")[2])
element.send_keys(i.split(",")[3])
效果:自动打开火狐浏览器,并在百度搜索框中输入"光荣之路"。接着代开第二个火狐浏览器窗口,并在搜狗搜索框中输入"汤达人"。
关键字驱动
这里没有分多个文件调用,直接写到一个.py文件中了。
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import time
def get_element(driver, locate_type, loacte_expression):
try:
element = WebDriverWait(driver,10).until(lambda x:x.find_element(by=locate_type,value=loacte_expression))
return element
except Exception as e:
raise e
#
def sleep_time(sleeptime):
time.sleep(sleeptime)
def init_webpage(url,sleeptime):
global driver
driver = webdriver.Firefox(executable_path="C:\geckodriver.exe")
driver.get(url)
sleep_time(sleeptime)
def search(locate_type,loacte_expression,value,sleeptime):
global driver
get_element(driver,locate_type,loacte_expression).send_keys(value)
sleep_time(sleeptime)
def quit():
global driver
driver.close()
#
with open(r"mykdt.txt","r",encoding='utf-8') as fp:
datas = fp.readlines()
for data in datas[1:]:
method = (data.split("||")[0]).strip()
locate_type = (data.split("||")[1]).strip()
loacte_expression = (data.split("||")[2]).strip()
value = (data.split("||")[3]).strip()
sleeptime = (data.split("||")[4]).strip()
if locate_type == "n" and loacte_expression == "n" and value != "n":
str_do = "%s('%s',%s)"%(method,value,sleeptime)
elif locate_type != "n" and loacte_expression != "n" and value != "n":
str_do = "%s('%s','%s','%s',%s)"%(method,locate_type,loacte_expression,value,sleeptime)
elif locate_type == "n" and loacte_expression == "n" and value == "n":
str_do = "%s()"%(method)
eval(str_do)