在本节中,将学习如何使用CSS - 标签和ID选择器查找特定的Web元素。
我们知道,查找特定的Web元素需要检查其HTML代码。
按照下面给出的步骤在示例网页上找到文本框。
右键单击示例网页上的文本框,然后选择“检查元素”
以下是文件(testing.html)的代码 -
Sample Test PageSample WebPage for Automation Testing
This is sample webpage with dummy elements that will help you in learning selenium automation.
This is sample text.
Link : Link to Yiibai
TextBox :
Button : Submit
Radio button :
Male
Female
Checkbox :
Automation Testing
Performance Testing
Drop down :
Automation Testing
Performance Testing
Manual Testing
Database Testing
Double-click to generate alert box
Click button to generate Alert box :
Generate Alert Box
Click button to generate Confirm box :
Generate Confirm Box
Drag and drop example- drag the below image on the textbox
function generateConfirmBox()
{
var x;
var r=confirm("Press a button!");
if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}
document.getElementById("demo").innerHTML=x;
}
function allowDrop(ev)
{
ev.preventDefault();
}
function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
使用右键查看元素的代码,如下所示:
它将启动一个窗口,其中包含开发文本框所涉及的所有特定代码。
记下它的标签及 id 属性的值。
用于通过CSS定位Web元素的Java语法 - 标记和ID选择器编写为:
driver.findElement(By.cssSelector("Tag#Value of id attribute"))
因此,要在示例网页上定位文本框,可使用输入标记及其id属性的值:
driver.findElement(By.cssSelector("input#fname"))
同样,要在示例网页上找到Submit按钮,可使用button标签及其id属性的值:
driver.findElement(By.cssSelector("button#idOfButton"))
创建了一个示例脚本,以便更好地理解如何使用CSS - 标记和ID选择器。在每个代码部分都嵌入了注释,这些注释将完成整个自动化过程。
package com.yiibai;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SampleOne {
public static void main(String[] args) {
// TODO Auto-generated method stub
// System Property for Gecko Driver
// System Property for Gecko Driver
System.setProperty("webdriver.gecko.driver", "D:\\software\\WebDriver\\geckodriver.exe");
System.setProperty("webdriver.firefox.bin", "D:\\Program Files\\Mozilla Firefox\\firefox.exe");
WebDriver driver = (WebDriver) new FirefoxDriver();
// Launch Website
driver.navigate().to("http://localhost/testing.html");
// Click on the textbox and send value
driver.findElement(By.cssSelector("input#fname")).sendKeys("Yiibai");
// Click on the Submit button using click() command
driver.findElement(By.cssSelector("button#idOfButton")).click();
// Close the Browser
//driver.close();
}
}
¥ 我要打赏
纠错/补充
收藏
加QQ群啦,易百教程官方技术学习群
注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。