selenium——键盘鼠标操作(二)
2019-07-25 本文已影响0人
小二哥很二
1.元素定位第二种写法:
from selenium import webdriver
from selenium.webdriver.common.by import By
options=webdriver.ChromeOptions()
options.add_argument('--headless')
driver=webdriver.Chrome(options=options)
driver.get('https://www.baidu.com/')
#result=driver.find_element(By.ID,'kw').is_displayed() 设置该元素用户是否可见,返回true false
driver.find_element(By.ID,'kw').send_keys(u'python')
driver.find_element(By.ID,'kw).sumbit() #sumbit,模拟提交,相当于直接回车了
2.鼠标事件
perform(): 执行所有ActionChain中存储的行为
context_click(): 右击
double_click(): 双击
drag_and_drop(): 拖动
move _to_element(): 鼠标悬停
1)Demo:
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains
driver=webdriver.Chrome()
driver.implicitly_wait(10)
driver.get('https://www.baidu.com/')
targetId=driver.find_element(By.ID,'su') #定位到要点击的元素
ActionChains(driver).context_click(targetId).perform() #右键点击了百度搜索
sleep(3)
above=driver.find_element_by_link_text('设置') #定位到要停留的元素
ActionChains(driver).move_to_element(above).perform() #鼠标停留在‘设置’元素上
sleep(2)
driver.quit()
2)Demo
drag_and_drop(source,target) #在源元素上按住鼠标左键,移动到目标元素上释放
element=driver.find_element_by_id('xx')
target=driver.find_element_by_id('xx')
ActionChains(driver).drag_and_drop(element,target).perform()
3.键盘操作
from seleniumimport webdriver
from selenium.webdriver.common.by import By
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
driver=webdriver.Chrome()
driver.implicitly_wait(10)
driver.get('https://www.baidu.com/')
sleep(2)
above=driver.find_element_by_link_text('设置') #定位要悬停在的元素
ActionChains(driver).move_to_element(above).perform() #鼠标悬停在‘设置’标签上
driver.find_element_by_id('kw').clear()
driver.find_element_by_id('kw').send_keys('seleniumm')
#删除多输入的一个m
driver.find_element_by_id('kw').send_keys(Keys.BACK_SPACE)
#在输入一个空格+教程
driver.find_element_by_id('kw').send_keys(Keys.SPACE)
driver.find_element_by_id('kw').send_keys('教程')
#全选所输入的内容
driver.find_element_by_id('kw').send_keys(Keys.CONTROL,'a')
sleep(2)
#剪切输入框内容
driver.find_element_by_id('kw').send_keys(Keys.CONTROL,'x')
sleep(2)
#将剪切的内容粘贴在输入狂中
driver.find_element_by_id('kw').send_keys(Keys.CONTROL,'v')
driver.find_element_by_id('kw').submit()
sleep(3)
print(driver.current_url)
driver.quit()
注:send_keys(Keys,键盘其它功能)