selenium行为链
一、行为链概述
1.为什么需要行为链
- 网站反爬:网站在服务器端设置验证程序,判断浏览器操作行为是否符合人类的行为
- 有更多的复杂操作,在自动化测试中经常使用
2.行为链如何使用
- (1)导入from senlium.webdriver.common.action_chains import ActionChains
- (2)创建对象actions = ActionChains(driver)
- (3)移动到某元素actions.move_to_element(element)
- (4)文本框填入内容actions.send_keys_to_element(element,‘python’)
- (5)单击actions.click(element)
- (6)双击actions.double_click(element)
- (7)右键点击actions.context_click(element)
二、代码演示
from selenium import webdriver
#导入selenium的行为链
from selenium.webdriver.common.action_chains import ActionChains
#构造浏览器
driver = chrome = webdriver.Chrome()
#登录网站
driver.get('https://cn.bing.com/')
#获取搜索框元素
input_tag = driver.find_element_by_id('sb_form_q') #获取到的是文本框
#获取搜索点击按钮
button = driver.find_element_by_id('sb_form_go') #获取到的是提交按钮
#创建行为链(更好的去模拟人的行为)
actions = ActionChains(driver)
actions.move_to_element(input_tag) #鼠标移动到文本框上
actions.send_keys_to_element(input_tag,'Python') #在文本框内输入搜索关键字
actions.move_to_element(button) #鼠标移动到提交按钮上
actions.click(button) #点击提交按钮
#开始执行行为链
actions.perform()