selenium学习记录
1 声明浏览器对象
from selenium import webdriver brower = webdriver.Chrome() brower = webdriver.Firefox() brower = webdriver.Edge() brower = webdriver.PhantomJS() brower = webdriver.Safari()
2 访问页面, 使用get方法访问页面
from selenium import webdriver brower = webdriver.Chrome() brower.get("http://www.baidu.com") print(brower.page_source) brower.close()
3 查找节点
from selenium import webdriver brower = webdriver.Chrome() brower.get("http://www.baidu.com") inputById = brower.find_element_by_id("kw") inputBySelector = brower.find_elements_by_css_selector("#kw") inputByXpath = brower.find_element_by_xpath("//*[@id='kw']") print(inputById, inputBySelector, inputByXpath)
以上分别使用id, css选择器, xpath方法获取节点, 结果如下, 是一致的
4 获取节点
brower.find_element_by_id() # 根据元素ID选择 brower.find_element_by_name() # 根据元素name属性选择 brower.find_element_by_link_text() # 根据元素中的文本部分选择 brower.find_element_by_partial_link_text() # 类似上一个, 有点模糊查询的意思 brower.find_element_by_xpath() # 根据xpath来选择元素 brower.find_element_by_tag_name() # 根据元素名称选择 brower.find_element_by_class_name() # 根据元素类名选择 brower.find_element_by_css_selector() # css选择器,
此外,selenium提供了一个通用的方法, find_element(),它需要传入两个参数, 查找方式和值
from selenium import webdriver from selenium.webdriver.common.by import By brower = webdriver.Chrome() brower.get("http://www.baidu.com") inputFirst = brower.find_element(By.ID, "kw") inputSecond = brower.find_element_by_id("kw") print(inputFirst == inputSecond)
可以看到, 以上两个方法完全是等值的,只不过使用起来会更加灵活
多个节点
如果要查找的元素在页面中存在多个, 那么使用find_element方法只能查询到第一个元素,这时就要使用find_elements()方法了, 与上面的方法相比仅仅是多了一个s, 查询结果为一个列表。列表中选择元素使用操作列表的方法来操作
5 页面交互 webdriver浏览器的属性 , 常见如下
# 获取当前URL brower.current_url # 获取当前页面源码 brower.page_source # 获取当前title brower.title # 获取当前测试浏览器名称 brower.name # 回退 brower.back() # 前进 brower.forward() # 获取当前浏览器句柄 brower.current_window_handle # 获取浏览器所有句柄 brower.window_handles # 浏览器最大化 brower.maximize_window() # 退出当前浏览器当前窗口 brower.quit() # 关闭当前浏览器所有窗口 brower.close() # 刷新页面 brower.refresh()
6 键盘交互
from selenium import webdriver import time from selenium.webdriver.common.keys import Keys brower = webdriver.Chrome("chromedriver.exe") brower.get("http://www.baidu.com") brower.find_element_by_id("kw").send_keys("自动化测试") time.sleep(3) # 删除选择元素中输入的文本, 类似于手动点击Backspace, * N代表点击几次 brower.find_element_by_id("kw").send_keys(Keys.BACK_SPACE*5) # 空格 brower.find_element_by_id("kw").send_keys(Keys.SPACE*4) # 输入 brower.find_element_by_id("kw").send_keys("学习"*5) # ctrl+a brower.find_element_by_id("kw").send_keys(Keys.CONTROL, "a") # ctrl+x brower.find_element_by_id("kw").send_keys(Keys.CONTROL, "x") # ctrl+v brower.find_element_by_id("kw").send_keys(Keys.CONTROL, "v") # 回车 brower.find_element_by_id("kw").send_keys(Keys.ENTER)
这个按照组合输入就行了,和键盘一样
7 ActionChains 类
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains as AC brower = webdriver.Chrome("chromedriver.exe") brower.get("http://www.baidu.com") gd = brower.find_element_by_link_text("设置") dj = brower.find_element_by_id("su") # 鼠标悬停, 右键百度一下, perform(), 执行ActionChains中的操作, 类似于数据库中的commit操作 AC(brower).move_to_element(gd).context_click(dj).perform()
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains as AC brower = webdriver.Chrome("chromedriver.exe") brower.get("http://www.baidu.com") brower.find_element_by_id("kw").send_keys("自动化测试") dj = brower.find_element_by_id("su") AC(brower).double_click(dj).perform()
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains as AC brower = webdriver.Chrome("chromedriver.exe") brower.get("http://sahitest.com/demo/dragDropMooTools.htm") dragger = brower.find_element_by_css_selector(".drag") item1 = brower.find_element_by_xpath("/html/body/div[2]") AC(brower).drag_and_drop(dragger, item1).perform()
8 执行JS
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains as AC brower = webdriver.Chrome("chromedriver.exe") brower.get("http://sahitest.com/demo/dragDropMooTools.htm") brower.execute_script("alert('自动化测试')")
9 获取节点信息
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains as AC brower = webdriver.Chrome("chromedriver.exe") brower.get("http://sahitest.com/demo/dragDropMooTools.htm") dragger = brower.find_element_by_id("dragger") # 通过get_attribute(),传入想要获取的属性名, 就可以的到属性值了 print(dragger.get_attribute("class")) # .text. 调用text属性, 获取节点内部文本信息 print(dragger.text) # 获取节点id print(dragger.id) # 获取相对位置 print(dragger.location) # 获取标签名称 print(dragger.tag_name) # 获取节点大小 print(dragger.size)
10 Frame
11 等待
隐式等待:比较官方的----当使用隐式等待执行测试的时候, 如果selenium没有Dom中找到节点, 将继续等待, 超出时间就报异常。
1 from selenium import webdriver 2 3 brower = webdriver.Chrome() 4 brower.implicitly_wait(10) 5 brower.get("http://www.baidu.com") 6 input = brower.find_element_by_id("kw") 7 print()
显式等待:比较官方的, 她指定要查找的节点, 然后指点一个最长的等待时间, 如果在规定的时间还没有加载出来这个节点, 就抛出超时异常, 找到就返回这个节点
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
brower = webdriver.Chrome()
title = brower.title
brower.get("http://www.baidu.com")
wait = WebDriverWait(brower, 10)
inputSk = wait.until(EC.presence_of_element_located((By.ID, "kw")))
print(inputSk)
#隐性等待和显性等待可以同时用,但要注意:等待的最长时间取两者之中的大者
12 expected_conditions模块
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC brower = webdriver.Chrome() brower.get("http://www.baidu.com") print(brower.title) titlebai = brower.title # 标题是某内容 title = EC.title_is(titlebai) # 包含部分title title2 = EC.title_contains("百度一下") # presence_of_element_located 判断某个元素是否被加到dom树下,不代表该元素一定可见 domElement = EC.presence_of_element_located((By.ID, "kw")) # 元素是否可见, 宽高不等于0, 元素没有隐藏 visibilityElement = EC.visibility_of_element_located((By.ID, "kw")) # 返回a元素对象列表 presenceelements = EC.presence_of_all_elements_located((By.TAG_NAME, "a")) # 判断节点中是否包含预期文本 locator1 = (By.PARTIAL_LINK_TEXT, '新闻') ecpresent_in_element = EC.text_to_be_present_in_element(locator1, titlebai)(brower) locator2 = (By.ID, "su") # 判断某个元素中的value属性值是否包含了预期字符串 present_in_element_value = EC.text_to_be_present_in_element_value(locator2, "百度一下")(brower) # 有弹窗返回弹窗对象, 没有返回false brower.execute_script("alert('现在是有弹窗的')") alert_is_present = EC.alert_is_present()(brower) # frame_to_be_availabe_and_switch_to_it:判断该frame是否可以switch进去,如果可以,则返回True并且switch进去,否则返回False # invisibility_of_element_located:判断某个元素是否不存在于dom树或不可见 # element_to_be_clickable:判断某个元素是见并且是enable(有效)的,这样的话才叫clickable # staleness_of:等某个元素从dom树下移除,返回True或False # element_to_be_selected:判断某个元素是否被选中,一般用于select下拉表 # element_selection_state_to_be 判断某个元素的选中状态是否符合预期 brower.close() print(alert_is_present)
其他的大同小异
13 cookie处理
from selenium import webdriver brower = webdriver.Chrome("chromedriver.exe") brower.get("http://www.baidu.com") # 增加cookie brower.add_cookie({'name':'mytest','value':'myvalue'}) # 获取全部cookie cookies = brower.get_cookies() print(cookies) # 获取单个cookie print(brower.get_cookie('mytest')) # 删除cookie brower.delete_cookie("mytest") brower.close()
14 截图
from selenium import webdriver import os, sys, time brower = webdriver.Chrome("chromedriver.exe") brower.implicitly_wait(5) pwd = os.getcwd() baseImagePath = os.path.dirname(pwd)+os.path.sep current_day = time.strftime("%Y_%m_%d", time.localtime(time.time())) current_time = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime(time.time())) imageDir = os.path.join(baseImagePath, "report",current_day+"\\") imageName = os.path.join(baseImagePath, "report",current_day+"\\") + current_time +".png" if not os.path.exists(imageDir): os.makedirs(imageDir) brower.get("https://baidu.com") brower.save_screenshot(imageName) brower.close()