標籤:
滑鼠事件:
ActionChains 類
? context_click() 右擊
? double_click() 雙擊
? drag_and_drop() 拖動
滑鼠右鍵:
from selenium.webdriver.common.action_chains import ActionChains #匯入ActionChains包
#定位到要右擊的元素qqq=driver.find_element_by_xpath("/html/body/div/div[2]/div[2]/div/div[3]/table/tbody/tr/td[2]")#對定位到的元素執行滑鼠右鍵操作ActionChains(driver).context_click(qqq).perform()‘‘‘#你也可以使用三行的寫法,但我覺得上面兩行寫法更容易理解chain = ActionChains(driver)implement =driver.find_element_by_xpath("/html/body/div/div[2]/div[2]/div/div[3]/table/tbody/tr/td[2]")chain.context_click(implement).perform()‘‘‘
滑鼠的其他動作:
#對定位到的元素執行滑鼠雙擊操作ActionChains(driver).double_click(qqq).perform()#執行元素的移動操作ActionChains(driver).drag_and_drop(element, target).perform()
定位一組元素:
from selenium import webdriverimport timeimport osdr = webdriver.Firefox()file_path = ‘file:///‘ + os.path.abspath(‘checkbox.html‘ )dr.get(file_path)# 選擇頁面上所有的 input,然後從中過濾出所有的 checkbox 並勾選之inputs = dr.find_elements_by_tag_name(‘input‘ )for input in inputs:if input.get_attribute(‘type‘ ) == ‘checkbox‘ :input.click()time.sleep(2)dr.quit()
方法二:
# -*- coding: utf-8 -*-from selenium import webdriverimport timeimport osdr = webdriver.Firefox()file_path = ‘file:///‘ + os.path.abspath(‘checkbox.html‘ )dr.get(file_path)# 選擇所有的 checkbox 並全部勾上checkboxes = dr.find_elements_by_css_selector(‘input[type=checkbox]‘ )for checkbox in checkboxes:checkbox.click()time.sleep(2)# 列印當前頁面上有多少個 checkboxprint len(dr.find_elements_by_css_selector(‘input[type=checkbox]‘ ))time.sleep(2)dr.quit()
# 把頁面上最後1個 checkbox 的勾給去掉dr.find_elements_by_css_selector(‘input[type=checkbox]‘ ).pop().click()time.sleep(2)
架構或視窗定位:
browser.switch_to_frame("f1")#再找到其下面的 ifrome2(id =f2)browser.switch_to_frame("f2")
#下面就可以正常的操作元素了
driver.switch_to_window("windowName")
selenium webdriver (3)