1、文本按钮操作相关:
- send_keys()输入文本
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("https://www.baidu.com/") time.sleep(2) dr.find_element_by_id("kw").send_keys("selenium")
- clear()清除文本
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("https://www.baidu.com/") time.sleep(1) dr.find_element_by_id("kw").send_keys("selenium") time.sleep(2) dr.find_element_by_id("kw").clear()
- click()点击按钮
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("https://www.baidu.com/") time.sleep(1) dr.find_element_by_id("kw").send_keys("selenium") time.sleep(1) dr.find_element_by_id("su").click()
- submit()类似输入文本后回车
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("https://www.baidu.com/") time.sleep(1) dr.find_element_by_id("kw").send_keys("selenium") time.sleep(1) dr.find_element_by_id("kw").submit()
- size 返回元素的尺寸
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("https://www.baidu.com/") time.sleep(1) print (dr.find_element_by_id("su").size)
- text 获取文本
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("http://192.168.0.161:8081/discuz/forum.php") time.sleep(1) print (dr.find_element_by_id("ls_fastloginfield_ctrl").text)
2、常见的 webdriver 方法
- get_window_size() 获取浏览器窗口大小
- set_window_size(480,800) 设置浏览器窗口大小
- maximize_window() 浏览器窗口最大化
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("https://www.baidu.com/") time.sleep(1) print (dr.get_window_size()) time.sleep(2) dr.maximize_window() time.sleep(2) dr.set_window_size(800,500)
- get_attribute()获取元素属性值
product_name = driver.find_element_by_id('currentItem').get_attribute("title") if name == product_name: print ("ok!") else: raise AssertionError
- back()向后
- forward()向前
- refresh()刷新
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("https://www.baidu.com/") time.sleep(1) dr.find_element_by_link_text("hao123").click() time.sleep(2) dr.back() time.sleep(2) dr.forward() time.sleep(2) dr.refresh()
- close()关闭当前选项卡页面
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("http://192.168.0.161:8081/discuz/forum.php") time.sleep(1) dr.find_element_by_link_text("交友").click() time.sleep(2) dr.close() #关闭当前句柄窗口
from selenium import webdriver from time import sleep dr = webdriver.Chrome() #打开第一个网页"百度" dr.get("https://www.baidu.com") sleep(2) #打开第二个网页"京东" js = 'window.open("https://www.jd.com")' dr.execute_script(js) sleep(2) #关闭当前句柄的窗口 dr.close()
- quit()关闭所有选项卡页面
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("http://192.168.0.161:8081/discuz/forum.php") time.sleep(1) dr.find_element_by_link_text("交友").click() time.sleep(2) dr.quit()
from selenium import webdriver from time import sleep dr = webdriver.Chrome() #打开第一个网页"百度" dr.get("https://www.baidu.com") sleep(2) #打开第二个网页"京东" js = 'window.open("https://www.jd.com")' dr.execute_script(js) sleep(2) #关闭当前浏览器 dr.quit()
- 窗口滚动操作
- js = "window.scrollTo(300,200)" #300表示左边距,200表示上边距
- js = "document.documentElement.scrollTop=200" #向下滑动200px
- js = "document.documentElement.scrollLeft=300" #向右滑动300px
- execute_script(js)
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("https://www.baidu.com/") time.sleep(1) dr.set_window_size(800,500) time.sleep(2) js = "window.scrollTo(300,200)" #300表示左边距,200表示上边距 dr.execute_script(js)
from selenium import webdriver from time import sleep dr = webdriver.Chrome() dr.get("https://www.cnblogs.com/ZhengYing0813") # print(dr.get_window_size()) dr.set_window_size(500,500) sleep(1) # js = "document.documentElement.scrollTop=200" #向下滑动200px # js = "document.documentElement.scrollLeft=300" #向右滑动300px # dr.execute_script(js) n = 0 while 1000 > n: n += 100 js = "document.documentElement.scrollTop=" + str(n) dr.execute_script(js) sleep(2) sleep(3) dr.quit()
- title 获取页面 title
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("http://192.168.0.161:8081/discuz/forum.php") time.sleep(1) print ("当前title:" + dr.title)
- current_window_handle 当前页面的句柄
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("http://192.168.0.161:8081/discuz/forum.php") time.sleep(1) print ("当前句柄:" + dr.current_window_handle) dr.find_element_by_link_text("交友").click() print ("当前句柄:" + dr.current_window_handle)
- window_handles 当前所有的句柄,返回句柄列表
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("http://192.168.0.161:8081/discuz/forum.php") time.sleep(1) print ("当前句柄:" + dr.current_window_handle) dr.find_element_by_link_text("交友").click() print ("所有句柄:" + dr.window_handles)
- switch_to_window() 切换窗口(一般通过句柄切换)
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("http://192.168.0.161:8081/discuz/forum.php") time.sleep(1) print ("首页title:" + dr.title) dr.find_element_by_link_text("交友").click() dr.switch_to_window(dr.window_handles[1]) print ("此时title:" + dr.title)
3、鼠标相关
- context_click()右击
- double_click()双击
- drag_and_drop()拖拽
- drag_and_drop_by_offset()拖拽
- move_to_element()鼠标悬停
- perform()执行
""" 鼠标悬浮 """ # 第一种方法(二次定位) from selenium import webdriver from time import sleep dr = webdriver.Chrome() dr.maximize_window() dr.get("https://www.baidu.com") sleep(2) dr.find_element_by_link_text("设置").click() dr.find_element_by_link_text("搜索设置").click() sleep(2) dr.quit() # 第二种方法 from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains #导入鼠标操作模块 import time #导入时间模块 dr = webdriver.Chrome() #webdriver类实例化 dr.get("https://www.baidu.com") time.sleep(1) element = dr.find_element_by_link_text("设置") #定位到鼠标要悬浮的元素 ActionChains(dr).move_to_element(element).perform() #鼠标操作类实例化,传driver驱动 将鼠标悬浮到元素上 执行悬浮操作 time.sleep(1) dr.find_element_by_link_text("高级搜索").click() #点击设置按钮下的元素 time.sleep(3) dr.close()
""" drag_and_drop 拖拽 """ sourse=driver.find_element_by_id('xx') #定位元素要移动的目标位置 target=driver.find_element_by_id('yy') #执行元素的拖放操作 ActionChains(driver).drag_and_drop(sourse,target).perform()
""" drag_and_drop_by_offset 拖拽,处理滑块验证 """ from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time dr = webdriver.Chrome() dr.get("https://shopcs.yunyoute.com/login") dr.maximize_window() dr.implicitly_wait(10) time.sleep(2) drag1 = dr.find_element_by_class_name("evenBox") # 定位到滑块 ActionChains(dr).drag_and_drop_by_offset(drag1,1572,708).perform() # 拖拽到指定坐标 (1572,708)
""" 鼠标右击操作 """ from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time dr = webdriver.Chrome() dr.get("https://shopcs.yunyoute.com/login") dr.maximize_window() dr.implicitly_wait(10) time.sleep(2) inp = dr.find_element_by_xpath('//*[@id="app"]/div/div[2]/div/div/div/div/div/div[3]/div[1]/input[2]') ActionChains(dr).context_click(inp).perform()
4、selenium 中三种等待方式
(1)线程等待(强制等待):time.sleep(s)
import time from selenium import webdriver dr = webdriver.Chrome() dr.get("https://www.baidu.com") dr.find_element_by_css_selector('[id=kw]').send_keys("selenium") time.sleep(2) dr.quit()
(2)隐式等待:dr.implicitly_wait(s) 等待页面所以的元素加载完成,则会自动进行下一步操做,如果等待时间超过设置的时间则会报错
from selenium import webdriver dr = webdriver.Chrome() dr.implicitly_wait(10) dr.get("https://www.baidu.com") dr.find_element_by_css_selector('[id=kw]').send_keys("selenium") dr.quit()
(3)显式等待:等待页面特定的某个元素加载后,才会进行下一步操作,如果在设定的时间内没有找到则会报错
from selenium import webdriver # 两种导入WebDriverWait方式 # from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support.ui import WebDriverWait #通过 as 关键字将 expected_conditions 重命名为EC from selenium.webdriver.support import expected_conditions as EC #导入By模块 from selenium.webdriver.common.by import By dr = webdriver.Chrome() dr.get("https://www.baidu.com") #presence_of_element_located 必须以元组的形式传入,所以使用到By方法进行定位 try: element = WebDriverWait(driver=dr,timeout=10,poll_frequency=0.5).until(EC.presence_of_element_located((By.ID,"kw"))) element.send_keys("selenium") finally: dr.quit()
- WebDriverWait(driver,timeout,poll_frequency,ignored_exceptions)
- driver:浏览器驱动
- timeout:最长超时时间,默认以秒为单位
- poll_frequency:检测的间隔(步长)时间,默认为 0.5S
- ignored_exceptions:超时后的异常信息,默认情况下抛 NoSuchElementException 异常
- WebDriverWait() 一般由 until() 或 until_not() 方法配合使用
until(method, message=' ') #调用该方法提供的驱动程序作为一个参数,直到返回值为True until_not(method, message=' ') #调用该方法提供的驱动程序作为一个参数,直到返回值为False
- EC 预置条件模块具有很多类型的判断:
- presence_of_element_located 判断当前元素是否存在
- presence_of_all_elements_located 判断一组元素是否存在
- text_to_be_present_in_element_value 判断元素值是否有xx文本信息
- presence_of_all_elements_located 判断一组元素是否存在
5、单 / 复选框相关
dr.get("http://127.0.0.1:8848/html/checkbox.html") list=dr.find_elements_by_xpath("//*[@class='tbmu']/td/label") for i in list: i.click()#勾选全部标签
6、下拉框处理
(1)select 模块定位
- Select 提供了三种选择方法:
- select_by_index(index) ——通过选项的顺序,第一个为 0
- select_by_value(value) ——通过 value 属性
- select_by_visible_text(text) ——通过选项可见文本
from selenium import webdriver from selenium.webdriver.support.select import Select import time dr = webdriver.Chrome() dr.get("http://127.0.0.1:8848/project/html/Drop_down_box.html") time.sleep(1) element = dr.find_element_by_id("birthprovince") Select(element).select_by_index(5) Select(element).select_by_value("山西省") Select(element).select_by_visible_text("河北省")
- Select 提供了四种方法取消选择:(只能取消选择多选选项)
- deselect_by_index(index)
- deselect_by_value(value)
- deselect_by_visible_text(text)
- deselect_all()
(2)二次定位(基本思路,先定位 select 框,再定位 select 里的选项)
from selenium import webdriver from selenium.webdriver.support.select import Select import time dr = webdriver.Chrome() dr.get("http://127.0.0.1:8848/project/html/Drop_down_box.html") time.sleep(1) #两次定位 element = dr.find_element_by_id("birthprovince") element.find_element_by_xpath('//*[@id="birthprovince"]/option[5]').click()
7、frame 处理
(1)switch_to.frame()选择一个 frame ---> 只能用 id 或 name 定位 frame
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("http://192.168.0.161:8081/discuz/forum.php") dr.maximize_window() dr.find_element_by_id("ls_username").send_keys("xfs") dr.find_element_by_id("ls_password").send_keys("123456") dr.find_element_by_css_selector('[type="submit"]').click() time.sleep(2) dr.find_element_by_link_text("学员作业专区").click() dr.find_element_by_xpath('//*[@id="newspecial"]/img').click() #发帖 time.sleep(2) dr.find_element_by_id("subject").send_keys("test") time.sleep(1) dr.switch_to_frame("e_iframe") #直接定位frame框架,只能通过id/name定位 time.sleep(1) dr.find_element_by_xpath('/html/body').send_keys(u"测试一下")
(2)假如 iframe 没有可定位的 id 或 name 那么可以通过 xpath 先定位到 iframe,再将对象传给 switch_to.frame():如下
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("http://192.168.0.161:8081/discuz/forum.php") dr.maximize_window() dr.find_element_by_id("ls_username").send_keys("zhengying") dr.find_element_by_id("ls_password").send_keys("zhengying123456") dr.find_element_by_css_selector('[type="submit"]').click() time.sleep(2) dr.find_element_by_link_text("学员作业专区").click() dr.find_element_by_xpath('//*[@id="newspecial"]/img').click() time.sleep(2) dr.find_element_by_id("subject").send_keys("test") time.sleep(1) frame = dr.find_element_by_css_selector("#e_body > div > iframe") #先定位到frame dr.switch_to.frame(frame) #再将frame的对象传进去 time.sleep(1) dr.find_element_by_xpath('/html/body').send_keys("dmlafjiuwnkdsncqwfcwnoqncsdknfwcnsdkfn")
(3)dr.switch_to.default_content() 取消选择一个 frame(跳回最外层的页面)
dr.switch_to.parent_frame() 取消选择一个 frame(跳出当前 frame)
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time dr.get("http://192.168.0.161:8081/discuz/forum.php") dr.maximize_window() dr.find_element_by_id("ls_username").send_keys("zhengying") dr.find_element_by_id("ls_password").send_keys("zhengying123456") dr.find_element_by_css_selector('[type="submit"]').click() time.sleep(2) dr.find_element_by_link_text("学员作业专区").click() dr.find_element_by_xpath('//*[@id="newspecial"]/img').click() time.sleep(2) dr.find_element_by_id("subject").send_keys("test") time.sleep(1) dr.switch_to_frame("e_iframe") #通过frame的id进行传参 dr.find_element_by_xpath('/html/body').send_keys(u"测试一下") time.sleep(2) dr.switch_to_default_content() time.sleep(2) dr.find_element_by_link_text("学员作业专区").click()
8、弹窗相关
- switch_to.alert.accept() #确定
- switch_to.alert.dismiss() #取消
- switch_to.alert.text #获取弹框信息
from selenium import webdriver import time dr = webdriver.Chrome() dr.get("http://127.0.0.1:8848/project/html/Alert.html") time.sleep(2) dr.find_element_by_class_name("xxx").click() time.sleep(2) # dr.switch_to_alert().accept() #确定 print (dr.switch_to_alert().text) #捕获弹窗内容 time.sleep(1) dr.switch_to_alert().dismiss() #取消
9、数据库操作
- dos窗口下安装pymysl --> pip install pymysql
- 游标概念:SQL 的游标是一种临时的数据库对象,游标的一个常见用途就是保存查询结果,以便后续调用或者使用(游标是系统为用户开设的一个数据缓冲区,存放 SQL 语句的执行结果)
- 游标 cursor():该方法会帮我们获取操作游标这时游标会为我们提供方法:
- 执行脚本命令
- 接受返回值
- db=pymysql.connect("IP 地址","用户名","密码","数据库名",charset='utf8')
- cursor=db.cursor() 获取游标
- fetchone() 提取第一行数据
- fetchall() 提取所有数据
- fetchmany(size) 根据 size 值提取具体行数
- 注意:当游标cursor中的某条数据被取出后,当前查询结果中则不能再次提取该条数据
import pymysql def con(ip,user,password,database,port,sql): db = pymysql.connect(ip,user,password,database,int(port),charset='utf8') cursor = db.cursor() cursor.execute(sql) print (cursor.fetchone()) print (cursor.fetchall()) print (cursor.fetchmany(5)) db.close() con("192.168.1.222","root","123456","study",3306,"select * from user;")