如何在 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.com/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()

更新于: 2020-07-29

1K+ 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.