一、webdriver基本使用命令
from selenium import webdriver # 导入webdriver模块
driver= webdriver.Chrome() # 打开Google浏览器
driver.get("https://www.baidu.com") # 打开 网址
#driver.get(r"C:\desktop\text.html") # 打开本地 html页面
try:
title = browser.title # 获取打开网址 的名字
url = browser.current_url # 获取打开网址的url
driver.maximize_window() #将浏览器最大化显示
driver.set_window_size(480, 800) #设置浏览器宽480、高800显示
driver.page_sourse #打印出页面源代码
driver.back() #浏览器后退
driver.forward() #浏览器前进
except:
#print("Oops! That was no valid number. Try again ")
driver.quit() #退出浏览器
driver.close() #关闭这个页面
二、标签导航
普通 定位标签 #查找标签
label1 = browser.find_element_by_id("kw")
label2 = browser.find_element_by_name("wd")
label3 = browser.find_element_by_class_name("s_ipt")
label4 = browser.find_element_by_tag_name("imput")
label5 = browser.find_element_by_link_text("a标签中的内容 准确定位")
label6 = browser.find_element_by_partial_link_text("a标签中的内容 模糊定位 ")
label7= browser.find_element_by_xpath(“放入 copy 标签中的常css路径”)
label8= browser.find_element_by_css_selector(“input=[id='id_name'/name='name_name'/……/]")
标签导航 xpath 标签定位复杂的情况下 考虑使用xpath
XPath即为XML路径语言,它是一种用来确定XML(标准通用标记语言的子集)文档中某部分位置的语言。XPath基于XML的树状结构,有不同类型的节点,包括元素节点,属性节点和文本节点,提供在数据结构树中找寻节点的能力。
# 绝对路径
label = driver.find_element_by_xpath("html/boday/p/input") # 绝对路径 导航
label = driver.find_element_by_xpath("html/boday/p/input[1]") # 绝对路径导航,多个input框,确定第一个input框
# 相对路径
label = driver.find_element_by_xpath("//input") # 相对路径导航 表示 整个文档当中的 input标签 默认为第一个 * 第一个“//” 表示 在整个文档中
label = driver.find_element_by_xpath("//input[2]") # 指定页面中的第二个 input框 没有就报错
# 父节点下找子节点
label = driver.find_element_by_xpath("//form//input") # // 父节点//子节点 * 返回子节点 input
label = driver.find_element_by_xpath("//form//input[2]") # // 父节点//子节点 [2] * 指定 父节点下的 第二个 input子节点
# 通过子节点 定位父节点
label = driver.find_element_by_xpath("//form//input/..") # 返回input的父节点 form 标签
label = driver.find_element_by_xpath("//form//input/.") # 当前节点
# 通过属性查找节点
label = driver.find_element_by_xpath("//input[@id]") # 相对路径导航 找到所有的 input标签 其中有 id属性的标签
label = driver.find_element_by_xpath("//input[@id='1']") # 属性查找 在所有的input标签中 找到 具有 id=1 的input标签
label = driver.find_element_by_xpath("//input[@name='xiahua']")
# 标签统计 countains
label = driver.find_element_by_xpath("//*[countains(input)=1]") # //* 表示 整个文档中 的所有标签,[count(input)=1] 表示 父标签下只有 一个input子标签 的 input标签
label = driver.find_element_by_xpath("//*[countains(input)=2]") # //* 表示 整个文档中 的所有标签,[count(input)=1] 表示 父标签下有 两个input子标签 的 input标签
# local-name 模糊查找
label = driver.find_element_by_xpath("//*[local-name()='input']") # 查找当前文档中 的所有input标签 默认返回第一个
label = driver.find_element_by_xpath("//*input") # 查找当前文档中 的所有input标签 默认返回第一个
label = driver.find_element_by_xpath("//*[local-name(),'i']") # 查找当前文档中 标签名字中 包含字母 i的标签,比如 input title
label = driver.find_element_by_xpath("//*[local-name(),'i']") # 查找当前文档中 的所有input标签 默认返回第一个
三、 模拟用户操作
label = driver.find_element_by_xpath("//*[local-name(),'i']")
label.get_attribute("type") # 显示标签的type属性 name type id placeholder
label.tag_name() # 获取标签名字 input p form ……
label.size
label.id
driver.maximize_window() # 窗口最大化 <br>>>> #模拟鼠标悬浮
label.click() # 模拟a标签 点击事件
label.send_keys("模拟搜索内容") # 模拟input框 输入内容
#label.clear() # 清除input标签中 输入的内容
# driver.back() # 模拟浏览器 返回上一个浏览页面
1、模拟鼠标操作
news = driver.find_element_by_xpath("//div[@id='u1']/a[1]").text
driver.find_elements_by_link_text("提交订单").click()
label_bel.click() # 模拟用户点击
其他鼠标操作
label.countext_lick() # 右击
label.double_click() # 双击
label.drag_and_drop() # 拖动
label.move_to_element # 悬浮
label.click_and_hold # 按鼠标左键一直不动
2、模拟键盘操作
from selenium.webdriver.common.keys import Keys # 引入模块
>>> label.send_keys("input输入的内容")
>>> label.send_keys(Keys.BACK_SPANCE) # 退格键
>>>label.send_keys(Keys.CONTRL,'a') # 全选
>>>label.send_keys(Keys.CONTRL,'v') # 粘贴
>>>label.send_keys(Keys.CONTRL,'c') # 复制
>>>label.send_keys(Keys.CONTRL,'x‘’) # 剪切
>>>label.send_keys(Keys.ENTER) # 回车
四、自带截图工具
python脚本实现自动登录
from selenium import webdriver
import time
#
# def take_screenshot(browser):
# browser.set_window_size(1200, 900)
# # 以下代码是将浏览器页面拉到最下面。
# browser.execute_script("""
# (function () {
# var y = 0;
# var step = 100;
# window.scroll(0, 0);
# function f() {
# if (y < document.body.scrollHeight) {
# y += step;
# window.scroll(0, y);
# setTimeout(f, 100);
# } else {
# window.scroll(0, 0);
# document.title += "scroll-done";
# }
# }
# setTimeout(f, 1000);
# })();
# """)
# time.sleep(5)
#
# if __name__ == "__main__":
# driver = webdriver.Chrome()
# driver.get("https://blog.youkuaiyun.com/weixin_40569991/article/details/81053850")
# take_screenshot(driver)
# # driver.get_screenshot_as_file("D:\\Python\\myblog\\baidu.png")
# driver.save_screenshot('D:\\Python\\myblog\\testxuexi\\自动化测试selenium模块\\baidu.png')
#
# driver.quit() # 看到所有window都被关闭
def take_screenshot(url, save_fn="自带截图.png"):
driver = webdriver.Chrome()
driver.set_window_size(1200, 900)
driver.get(url) # Load page
driver.execute_script("""
(function () {
var y = 0;
var step = 100;
window.scroll(0, 0);
function f() {
if (y < document.body.scrollHeight) {
y += step;
window.scroll(0, y);
setTimeout(f, 100);
} else {
window.scroll(0, 0);
document.title += "scroll-done";
}
}
setTimeout(f, 1000);
})();
""")
for i in range(3):
if "scroll-done" in driver.title:
break
time.sleep(2)
driver.save_screenshot(save_fn) # 截图
driver.close()
if __name__ == "__main__":
take_screenshot("https://blog.youkuaiyun.com/BBBrian88")
五、控制多窗口
# coding=utf-8
from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.maximize_window() # 窗口最大化
driver.get('https://www.baidu.com') # 在当前浏览器中访问百度
time.sleep(2)
#print(driver.current_window_handle)# 输出当前窗口句柄(百度)
frist_handle = driver.current_window_handle
# 新开一个窗口,通过执行js来新开一个窗口,访问搜狗
js='window.open("https://www.sogou.com");'
driver.execute_script(js)
# 再新开一个窗口,通过执行js来新开一个窗口,访问有道
js='window.open("http://www.youdao.com/");'
driver.execute_script(js)
handles = driver.window_handles # 获取当前窗口句柄集合(列表类型)
print(handles) # 输出句柄集合
for handle in handles:# 切换窗口(切换到有道)
if handle != frist_handle:
driver.switch_to.window(handle)
#print(driver.current.window_handle) # 输出当前窗口句柄(有道)
driver.find_element_by_id("translateContent").send_keys("selenium") #有道翻译selenium
driver.find_element_by_css_selector("button").click()
#driver.find_element_by_css_selector("[data-rlog='search-popup-close-win']").click()
driver.find_element_by_css_selector("[class='close js_close']").click() #关闭弹窗
driver.get_screenshot_as_file("D:\Python\myweb\my-testxuexi\自动化测试selenium\\youdao.jpg") # 截图 可自定义截图后的保存位置(D:\windows)和图片命名(youdao.jpg)
time.sleep(5)
break
driver.close() #关闭当前窗口(有道)
for handle in handles:# 切换窗口(切换到搜狗)
if handle != frist_handle:
driver.switch_to.window(handles[-1]) #此时只剩两个句柄,取最后一个
#print(driver.current_window_handle) # 输出当前窗口句柄(搜狗)
driver.find_element_by_id("query").send_keys("selenium") #搜狗搜索selenium
driver.find_element_by_id("stb").click()
time.sleep(2) #等待2s为了截完整搜索结果图
driver.get_screenshot_as_file("D:\Python\myweb\my-testxuexi\自动化测试selenium\\sougou.jpg") # 截图 可自定义截图后的保存位置和图片命名
time.sleep(5)
break
driver.close() #关闭当前窗口(搜狗)
#driver.switch_to_window(frist_handle) #切换回百度窗口
driver.switch_to.window(handles[0]) #切换回百度窗口
driver.find_element_by_id("kw").send_keys("selenium") #百度搜索selenium
driver.find_element_by_id("su").click()
time.sleep(2) #等待2s为了截完整搜索结果图
driver.get_screenshot_as_file("D:\Python\myweb\my-testxuexi\自动化测试selenium\\baidu.jpg") #截图 可自定义截图后的保存位置和图片命名
time.sleep(5)
driver.quit() #退出浏览器
六、打开页面手动输入多个网页复制到text中
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys # 模拟键盘操作
import time
from selenium.webdriver import ActionChains #鼠标操作
# ---------------手动打开指定页面 # phantomjs 无见面炒作浏览器,就是看不见操作
# https://blog.youkuaiyun.com/weixin_39552387/article/details/84100944 # 用selenium控制已打开的浏览器
# 还有,不要忘了在环境变量中PATH里将chrome的路径添加进去。 如下解决
# C:\Users\IBMIBM\AppData\Local\Google\Chrome\Application\chrome.exe 不是这个
# 不过我的是这种C:\Users\IBMIBM\AppData\Local\Google\Chrome\Application就是谷歌的安装目录,(右击谷歌选择打开文件位置就行了)
# PATH中 添加 这个东西 chrome浏览器安装的位置
# 运行 1步 打开cmd,在命令行中输入命令:
# chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\selenum\AutomationProfile"
# 2步 此时会打开一个浏览器页面,我们手动输入百度网址,我们把它当成一个已存在的浏览器:
# 手动输入 http://www.beidu.com/以后就 在这里 3步 运行程序
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") #不用管他了
chrome_driver = "D:\Python\python\Scripts\chromedriver.exe" # 自己安装的位置chromedriver.exe
driver = webdriver.Chrome(chrome_driver, options=chrome_options)
# ------------------
# driver_1 = webdriver.Chrome() # 打开新的 Google浏览器3.7# 自己打开固定页面
# driver_1.get('https://www.baidu.com')
#
# driver.switch_to.window(windows[-1]) # 获取几个页面最后一个页面
handles = driver.window_handles # 获取当前窗口句柄集合(列表类型)
print(handles) # 输出句柄集合
for i in handles: # for 循环语句
print(i)
# driver.find_element_by_tag_name('company').click()
# currentPageUrl = driver.current_url # 获取当前页面url并断言
#print("当前页面的url是:", currentPageUrl, driver.title)
element = driver.find_element_by_tag_name('body')
element.send_keys(Keys.CONTROL, 'a') # 全选(Ctrl+A)
element.send_keys(Keys.CONTROL, 'c') # 复制(Ctrl+C)
driver.find_element_by_id("kw").send_keys(Keys.CONTROL, 'v')
# driver.find_element_by_xpath("//div[@id='u1']/a[1]").text
# 吧复制的东西 保成到text 获取元素属性值 get_attribute
news = driver.find_element_by_id("kw").get_attribute('value')
# news = driver.page_source # 获取当前打开的网页html内容
news = news + i
#f = open('/Users/michael/test.txt', 'w')
with open("1.txt", "w", encoding='utf-8') as f:
f.write(news)
f.close()
# driver.refresh() # 刷新打开的页面
time.sleep(3)
# ---------------------------------
# js = 'window.open("https://www.sogou.com");' # 在同一个浏览器中打开页面
# driver.execute_script(js)
# execute_script() 是同步方法,用它执行js代码会阻塞主线程执行,直到js代码执行完毕;
# execute_async_script() 方法是异步方法,它不会阻塞主线程执行。
# 这个 新窗口不能关闭
# -----------------------------------------
driver.get('http://www.so.com') # 替换上一个网页
driver.find_element_by_id("input").send_keys(Keys.CONTROL, 'v')
time.sleep(2)
driver.close() # 只会关闭当前页面
# 新开一个窗口,通过执行js来新开一个窗口,访问搜狗
driver_1 = webdriver.Chrome() # 打开新的 Google浏览器3.7# 自己打开固定页面
driver_1.get('https://www.baidu.com')
driver_1.find_element_by_id("kw").send_keys(Keys.CONTROL, 'v')
time.sleep(5)
driver_1.close() # 只会关闭当前页面
for h in range(0, len(handles)):
aa = len(handles) - h
else: # 循环的 else 部分
print(i)
driver.switch_to.window(handles[aa]) # 获取几个页面最后一个页面 切换到主页面
# 实现打开新窗口后, 原窗口不可操作, 关闭新窗口后, 原窗口才可操作
# handles = driver.window_handles # 获取当前窗口句柄集合(列表类型)
# 切换到首页句柄
# # 移动浏览器观看展示
# driver.set_window_size(width=500, height=500, windowHandle="current")
#driver.set_window_position(x=1000, y=100, windowHandle='current')
# driver.quit() # 看到所有window都被关闭