1. 程式人生 > >Selenium3+webdriver學習筆記5(模擬常用鍵盤和滑鼠事件)

Selenium3+webdriver學習筆記5(模擬常用鍵盤和滑鼠事件)

#!/usr/bin/env python
# -*- coding:utf-8 -*-

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

import time,os

# about:addons 火狐瀏覽器安裝元件,訪問的地址

# <input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off">
# <input type="submit" value="百度一下" id="su" class="btn self-btn bg s_btn">
#id
keys="selenium自動化"
delay=3
url="https://www.baidu.com/"
driver=webdriver.Firefox()

driver.get(url)

#等待delay秒
driver.implicitly_wait(delay)

#輸入字串
driver.find_element_by_id("kw").send_keys(keys)

#清空輸入的內容
driver.find_element_by_id("kw").clear()

#滑鼠左鍵點選
driver.find_element_by_id("su").click()

driver.find_element_by_id("kw").send_keys(keys)

#模擬回車提交表單
driver.find_element_by_id("kw").submit()

driver.find_element_by_id("kw").send_keys(Keys.ENTER)

#複製 貼上 全選 剪下 製表鍵 f11~f12
driver.find_element_by_id("kw").send_keys(keys,Keys.CONTROL,'c')

driver.find_element_by_id("kw").send_keys(keys,Keys.CONTROL,'v')

driver.find_element_by_id("kw").send_keys(keys,Keys.CONTROL,'a')

driver.find_element_by_id("kw").send_keys(keys,Keys.CONTROL,'x')

driver.find_element_by_id("kw").send_keys(Keys.TAB)

driver.find_element_by_id("kw").send_keys(Keys.F1)

#執行ActionChains中的所有行為
source=driver.find_element_by_link_text("設定")
target=driver.find_element_by_link_text("新聞")

# 滑鼠懸停
ActionChains(driver).move_to_element(source).perform()

# 右擊滑鼠
ActionChains(driver).context_click(source).perform()

# 雙擊滑鼠
ActionChains(driver).double_click(source).perform()

#滑鼠移動到另一個位置
ActionChains(driver).drag_and_drop(source,target).perform()

# 滑鼠左鍵
ActionChains(driver).click_and_hold(source).perform()


#等待delay秒
time.sleep(delay)

driver.quit()