如何在 Selenium 中使用 Python 將字母輸入到編輯框中並使其大寫?
我們可以藉助 Action Chains 類在 Selenium 中將字母輸入到編輯框中並使其大寫。這些類通常用於自動化諸如上下文選單點選、滑鼠按鈕操作、按鍵和滑鼠移動等互動操作。
這些型別的操作主要在複雜的場景中很常見,例如拖放和將滑鼠懸停在頁面上的元素上。Action Chains 類的這些方法被高階指令碼所使用。我們可以藉助 Selenium 中的 Action Chains 來操作 DOM。
動作鏈物件以佇列的形式實現 ActionChains,然後執行 perform() 方法。呼叫 perform() 方法後,動作鏈上的所有操作都將被執行。
建立動作鏈物件的示例如下:
首先,我們需要匯入 Action Chain 類,然後將驅動程式作為引數傳遞給它。
現在,藉助這個物件,可以執行所有動作鏈操作。
語法
建立 Action Chains 物件的語法:
from selenium import webdriver
# import Action chains from selenium.webdriver import ActionChains # create webdriver object driver = webdriver.Firefox() # create action chain object action = ActionChains(driver)
建立 Action Chains 物件後,我們可以像佇列一樣依次執行多個操作。
為了在編輯框中輸入大寫字母,我們需要首先將焦點移動到編輯框,然後執行 click() 操作。然後按住 SHIFT 並使用 send_keys() 方法輸入字母。最後,使用 perform() 執行所有這些排隊的操作。
語法
#element source = driver.find_element_by_id("name") #action chain object action = ActionChains(driver) # move the mouse to the element action.move_to_element(source) # perform click operation on the edit box action.click() # perform clicking on SHIFT button action.key_down(Keys.SHIFT) # input letters in the edit box action.send_keys('tutorialspoint') # perform the queued operation action.perform()
示例
輸入大寫字母的程式碼實現。
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/index.htm") #to refresh the browser driver.refresh() # identifying the source element source= driver.find_element_by_xpath("//input[@name='search']"); # action chain object creation action = ActionChains(driver) # move the mouse to the element action.move_to_element(source) # perform click operation on the edit box action.click() # perform clicking on SHIFT button action.key_down(Keys.SHIFT) # input letters in the edit box action.send_keys('tutorialspoint') # perform the queued operation action.perform() #to close the browser driver.close()
廣告