Selenium 简明教程
Selenium WebDriver - User Interactions
Selenium WebDriver 可用于各种用户交互,例如单击链接或按钮,从输入框输入或清除文本,以及在下拉列表中选择或取消选择选项。
Selenium WebDriver can be used for various user interactions like clicking a link or a button, entering or clearing text from an input box, and selecting or deselecting options in a dropdown.
Basic Selenium Webdriver Commands on User Interactions
Selenium Webdriver 中有多个命令可以帮助对元素执行操作。它们如下所列:
There are multiple commands in Selenium Webdriver that help to perform an action on an element. They are listed below −
click()
此方法用于即使在元素中间也能执行单击。如果元素中间被隐藏,则会抛出异常。
This method is used to perform a click even at the middle of an element. In case, middle of an element is hidden, an exception would be thrown.
右键单击网页,然后单击 Chrome 浏览器中的“检查”按钮。然后,页面的相关 HTML 代码将被打开。要调查下方的链接 say No Content ,请单击 HTML 代码顶部的左上箭头,如下所示高亮显示。
Right click on the web page, and click on the Inspect button in the Chrome browser. Then, the relevant HTML code for the page would be opened. For investigating a link say No Content in the below page, click on the left upward arrow at the top of the HTML code as highlighted below.
一旦我们单击并用箭头指向“无内容”超链接,其 HTML 代码就会可见。可以使用链接文本定位器检测链接。使用此方法,将找到链接文本匹配值对应的第一个链接。
Once, we had clicked and pointed the arrow to the No Content hyperlink, its HTML code was visible. A link can be detected using the link text locator. Using this, the first link with the matching value of the link text is located.
让我们举一个示例,首先单击 No Content 链接,然后获取 Link has responded with status 204 and status text 文本。
Let us take an example, where we would first click the No Content link, after which we would obtain the text Link has responded with status 204 and status text.
代码实现
Code Implementation
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import java.util.concurrent.TimeUnit;
public class Lnks {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new EdgeDriver();
// adding implicit wait of 15 secs
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
// Opening the webpage where we will identify link
driver.get("https://www.tutorialspoint.com/selenium/practice/links.php");
// Identify link with link text
driver.findElement(By.linkText("No Content")).click();
// identify text
WebElement l = driver.findElement(By.xpath("/html/body/main/div/div/div[2]/div[2]"));
// Get text after clicking the link
System.out.println("Text is: " + l.getText());
// Closing browser
driver.quit();
}
}
Text is: Link has responded with status 204 and status text No Content
Process finished with exit code 0
在上述示例中,在单击链接 No Content 后获得的文本为 Text is: Link has responded with status 204 and status text No Content 。
In the above example, the text obtained after clicking on the link No Content was Text is: Link has responded with status 204 and status text No Content.
最后,收到了消息 Process finished with exit code 0 ,表示代码成功执行。
Finally, the message Process finished with exit code 0 was received, signifying successful execution of the code.
sendKeys()
此方法用于在编辑框或任何可编辑字段中输入一些文本。每个输入框都有称为输入的标签名。此外,输入框应具有值文本的类型属性。如果一个元素不可编辑,并且 sendKeys() 方法被应用于它,则应该抛出异常。
This method is used to enter some text in the edit box or any editable field. Every input box has the tagname known as the input. Also, an input box should have the type attribute having the value as text. If an element is not editable, and sendKeys() method is applied on it, an exception should be thrown.
clear()
此方法用于清除编辑框或任何可编辑字段中的文本。如果一个元素不可编辑,并且 clear() 方法被应用于它,则应该抛出异常。
This method is used to clear text from an edit box or any editable field. If an element is not editable, and a clear() method is applied on it, an exception should be thrown.
让我们来看上述页面的一个示例,首先使用 sendKeys() 方法在输入框中输入一些文本。要输入的值作为参数传递给该方法。然后,我们用 clear() 方法擦除输入的文本。
Let us take an example of the above page, where we would first enter some text in the input box with the help of the sendKeys() method. The value to enter is passed as an argument to the method. Then, we would wipe out the text entered with the clear() method.
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class InptBox {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new ChromeDriver();
// adding implicit wait of 15 secs
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
// Opening the webpage where we will identify edit box and enter
driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");
// Identify the input box with xpath locator
WebElement e = driver.findElement(By.xpath("//*[@id='name']"));
// enter text in input box
e.sendKeys("Selenium");
// Get the value entered
String text = e.getAttribute("value");
System.out.println("Entered text is: " + text);
// clear the text entered
e.clear();
// Get no text after clearing text
String text1 = e.getAttribute("value");
System.out.println("Get text after clearing: " + text1);
// Closing browser
driver.quit();
}
}
Entered text is: Selenium
Get text after clearing:
Process finished with exit code 0
在上述示例中,我们首先在输入框中输入 Selenium 文本,并通过消息 Entered text is: Selenium 在控制台中检索输入的值。然后清除输入的值,输入框中没有值。因此,我们在控制台中收到消息: Get text after clearing 。
In the above example, we had first entered the text Selenium in the input box, and retrieved the value entered in the console with the message- Entered text is: Selenium. Then cleared the value entered and there was no value in the input box. Hence, we received the message in the console: Get text after clearing.
Select Class
Select 类中有多个方法可以帮助我们与下拉列表交互。每个下拉列表都由 select 标签名标识,并且其选项由选项标签名标识。网页上可能存在两种类型下拉列表——单选(允许选择一个选项)和多选(允许选择多个选项)。多选下拉列表还应有一个多重属性。
There are multiple methods on Select class that help us to interact with dropdown. Every dropdown is identified by the select tagname and its options are identified with the option tagname. There can be two types of dropdown on a web page - single select(allows selection one option) and multiple select(allows selection more than one option). A multiple select dropdown should also have an attribute multiple.
在上面的图片中,选项 Pick one title 具有 selected 属性,表示它被默认选中。Select 类中有多个方法允许处理 dropdowns in Selenium Webdriver 。
In the above image, the option Pick one title has the attribute selected, meaning this is selected by default. There are multiple methods in the Select class which allows handling of dropdowns in Selenium Webdriver.
在下面的页面中,我们将访问文本“多选下拉列表”旁边的多选下拉列表,选择 Electronics & Computers 和 Sports & Outdoors 值,并执行一些验证。
In the below page, where we would access the multi-select dropdown beside the text Multi Select drop down, select the values Electronics & Computers and Sports & Outdoors, and perform some validations.
package org.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class SelectMultipleDropdowns {
public static void main(String[] args) throws InterruptedException {
// Initiate the Webdriver
WebDriver driver = new ChromeDriver();
// adding implicit wait of 15 secs
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
// Opening the webpage where we will get dropdown
driver.get("https://www.tutorialspoint.com/selenium/practice/select-menu.php");
// identify multiple dropdown
WebElement dropdown = driver.findElement
(By.xpath("//*[@id='demo-multiple-select']"));
// object of Select class
Select select = new Select(dropdown);
// gets options of dropdown in list
List<WebElement> options = select.getOptions();
for (WebElement opt : options){
System.out.println("Options are: " + opt.getText());
}
// return true if multi-select dropdown
Boolean b = select.isMultiple();
System.out.println("Boolean value for multiple dropdown: "+ b);
// select item by value
select.selectByValue("3");
// select item by index
select.selectByIndex(7);
// get all selected options of dropdown in list
List<WebElement> selectedOptions = select.getAllSelectedOptions();
for (WebElement opt : selectedOptions){
System.out.println("Selected Options are: " + opt.getText());
}
// get first selected option in dropdown
WebElement f = select.getFirstSelectedOption();
System.out.println("First selected option is: "+ f.getText());
// deselect option by index
select.deselectByIndex(7);
// deselect all selected items
select.deselectAll();
// get all selected options of dropdown after deselected
List<WebElement> delectedOptions = select.getAllSelectedOptions();
System.out.println("No. options selected: " + delectedOptions.size());
// Closing browser
driver.quit();
}
}
Options are: Books
Options are: Movies, Music & Games
Options are: Electronics & Computers
Options are: Home, Garden & Tools
Options are: Health & Beauty
Options are: Toys, Kids & Baby
Options are: Clothing & Jewelry
Options are: Sports & Outdoors
Boolean value for multiple dropdown: true
Selected Options are: Electronics & Computers
Selected Options are: Sports & Outdoors
First selected option is: Electronics & Computers
No. options selected: 0
Process finished with exit code 0
在上面的示例中,我们使用控制台中的消息 - Options are: Books, Options are: Movies, Music & Games, Options are: Home, Garden & Tools, Options are: Health & Beauty, Options are: Toys, Kids & Baby, Options are: Clothing & Jewelry, Options are: Sports & Outdoors 获取了下拉列表中的所有选项。我们还使用控制台中的消息 - Boolean value for checking is: true 验证下拉列表具有多选选项。
In the above example, we had obtained all the options of the dropdown with the message in the console - Options are: Books, Options are: Movies, Music & Games, Options are: Home, Garden & Tools, Options are: Health & Beauty, Options are: Toys, Kids & Baby, Options are: Clothing & Jewelry, Options are: Sports & Outdoors. We had also validated that the dropdown had multiple selection options with the message in the console - Boolean value for checking is: true.
我们使用控制台中的消息 Selected Options are: Electronics & Computers, Selected Options are: Sports & Outdoors 检索了下拉列表中的选中选项。我们还使用控制台中 First selected option is: Electronics & Computers 消息获取了第一个选中的选项。最后,我们取消选择下拉列表中所有选中的选项,因此我们在控制台中得到消息 No. options selected: 0 。
We had retrieved the selected options in the dropdown with the message in the console - Selected Options are: Electronics & Computers, Selected Options are: Sports & Outdoors. We had also obtained the first selected option with the message in the console - First selected option is: Electronics & Computers. Finally, we deselected all the selected options in the dropdown, and hence obtained the message in the console - No. options selected: 0.
Scrolling Action
Selenium webdriver 可用于在网页上执行滚动操作,借助 JavaScriptExecutor(一个接口)。Selenium Webdriver 可以使用 JavaScriptExecutor 执行 JavaScript 命令。
Selenium webdriver can be used to do scrolling actions on a web page with the help of the JavaScriptExecutor(an interface). Selenium Webdriver can execute the JavaScript commands using the JavaScriptExecutor.
Read More: Selenium Webdriver Scroll Operations 。
Read More: Selenium Webdriver Scroll Operations.
Conclusion
这就概括了我们对 Selenium WebDriver 用户操作教程的全面见解。我们已开始描述有关用户操作的 Selenium WebDriver 基本命令,并举例说明如何在 Selenium WebDriver 中使用这些命令。这使你能够深入了解 Selenium WebDriver 用户操作。明智的做法是不断练习你所学内容,并探索与 Selenium 相关的其他内容来加深你的理解并拓宽你的视野。
This concludes our comprehensive take on the tutorial on Selenium WebDriver User Interactions. We’ve started with describing basic Selenium Webdriver commands on User Interactions, and examples to illustrate how to work with these commands in Selenium Webdriver. This equips you with in-depth knowledge of the Selenium WebDriver User Interactions. It is wise to keep practicing what you’ve learned and exploring others relevant to Selenium to deepen your understanding and expand your horizons.