如何在使用Python的Selenium中按下頁面上的ctrl +f鍵?
我們可以使用Selenium執行按下ctrl+f鍵的操作。Selenium提供了多個特殊鍵,允許我們模擬鍵盤按鍵操作,例如ctrl+c、ctrl+v、ctrl+f等等。這些特殊鍵屬於**selenium.webdriver.common.keys.Keys類**。
key_up() – 此方法釋放修飾鍵。key_up()方法是Action Chains類的一部分,用於釋放透過key_down()按下的鍵。此方法廣泛用於複製貼上操作(ctrl+c,ctrl+v)。
為了執行此操作,我們需要先按下ctrl鍵,然後同時按下F鍵。這兩個步驟可以透過key_up()方法自動化,並且只能與Shift、Alt和Control鍵一起使用。
語法
key_up(args1, args2)
這裡args1是要傳送的鍵。該鍵在Keys類中定義。
args2引數是要傳送按鍵的元素。如果省略,則會將按鍵傳送到當前獲得焦點的元素。
示例
按下ctrl+f的程式碼實現。
from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://tutorialspoint.tw/about/about_careers.htm") #to refresh the browser driver.refresh() # action chain object creation a = ActionChains(driver) # perform the ctrl+f pressing action a.key_down(Keys.CONTROL).send_keys('F').key_up(Keys.CONTROL).perfo rm() #to close the browser driver.close()
廣告