Selenium 简明教程

Selenium Webdriver - Handling Edit Boxes

Selenium 可以用来向编辑框输入文本。编辑框由输入标记表示,并且其类型属性应该具有文本值。它可以使用 id、类、名称、css、xpath 和标记名等任何定位符来识别。

Selenium can be used to input text to an edit box. An edit box is represented by the input tag and its type attribute should have the value as text. It can be identified with any of the locators like - id, class, name, css, xpath and tagname.

要向编辑框中输入值,我们必须使用 send_keys 方法。

To input a value into an edit box, we have to use the method send_keys.

让我们看看一个 web 元素的 html 代码:

Let us see the html code of a webelement −

handling edit boxes

上图中高亮的编辑框标记名称为 input。让我们在识别出该元素后尝试在此编辑框中输入一些文本。

The edit box highlighted in the above image has a tagname - input. Let us try to input some text into this edit box after identifying it.

Code Implementation

处理编辑框的代码实现如下 -

The code implementation for handling edit box is as follows −

from selenium import webdriver

#set chromedriver.exe path
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')

#url launch
driver.get("https://www.tutorialspoint.com/index.htm")

#identify edit box with tagname
l = driver.find_element_by_tag_name('input')

#input text
l.send_keys('Selenium Python')

#obtain value entered
v = l.get_attribute('value')
print('Value entered: ' + v)

#driver close
driver.close()

Output

handling edit boxes output

输出显示了信息 - 进程退出代码 0,表明上述 Python 代码已成功执行。此外,在编辑框中输入的值(从 get_attribute 方法获取) - Selenium Python 会在控制台打印出来。

The output shows the message - Process with exit code 0 meaning that the above Python code executed successfully. Also, the value entered within the edit box (obtained from the get_attribute method) - Selenium Python gets printed in the console.