如何在 Python 中的 Selenium 中输入编辑框的值?


我们可以借助下面列出的方法在 Selenium 中输入编辑框的值 -

  • 使用 send_keys 方法。

    此方法可以通过利用键类向编辑框发送任何文本或按下键。

  • 使用 Javascript 执行程序。

    Javascript 文档对象模型可以处理页面上的任何元素。Javascript 运行于客户端,对网页执行操作。Selenium 能够借助 execute_script() 方法执行 Javascript 脚本。我们可以借助此方法输入任何编辑框的值。

示例

使用 send_keys 方法进行代码实现。

from selenium import webdriver
#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 edit box and entering text with send_keys method
driver. find_element_by_css_selector("input[class='gsc-input']").
send_keys("Selenium")
#to close the browser
driver.close()

使用 Javascript 执行程序进行代码实现。

from selenium import webdriver
#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()
# enter text with the Javascript executor
driver.execute_script(
"document.getElementsByName('search')[0].value = 'Selenium' ;")
#to close the browser
driver.close()

更新于: 2020 年 7 月 29 日

863 次浏览

开启您的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.