Selenium教程

Selenium 定位策略-(通过CSS标签和属性)

在本节中,您将学习如何使用CSS(标签和属性选择器)来定位特定的网络元素。
我们知道,定位特定的Web元素会涉及对其HTML代码的检查。
请按照以下步骤在示例Web页面上找到Textbox。
打开URL: https://www.testandquiz.com/selenium/testing.html 右键单击示例网页上的"文本框",然后选择"检查元素" 定位策略-通过CSS标签和属性 它将启动一个窗口,其中包含开发文本框所涉及的所有特定代码。 定位策略-通过CSS标签和属性 记下其标记和属性。
注意: 通过CSS-标记和属性选择器定位时,可以选择诸如id,class和name之类的属性及其值。
在这里,我们将记下它的标签和id属性的值。 定位策略-通过CSS标签和属性
用于通过CSS定位Web元素的Java语法-标签和属性选择器的编写方式为:
driver.findElement(By.cssSelector("Tag[Attribute=value]"))
    
因此,为了在示例网页上定位文本框,我们将使用具有id属性的输入标签:
driver.findElement(By.cssSelector("input[id=fname]"))
    
类似地,为了在示例网页上定位Submit按钮,我们将使用具有id属性的button标记:
driver.findElement(By.cssSelector("button[id=idOfButton]"))
    
我们为您创建了一个示例脚本,以使您更好地了解如何使用CSS-标记和属性选择器。我们在代码的每个部分都嵌入了注释,这些注释将指导您完成整个自动化过程。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class SampleThree {
    public static void main(String[] args) {
        
     // System Property for Gecko Driver 
System.setProperty("webdriver.gecko.driver","D:\\GeckoDriver\\geckodriver.exe" );
        
       // Initialize Gecko Driver using Desired Capabilities Class
        DesiredCapabilities capabilities = DesiredCapabilities.firefox();
        capabilities.setCapability("marionette",true);
        WebDriver driver= new FirefoxDriver(capabilities);
        
    
      // Launch Website
driver.navigate().to("https://www.testandquiz.com/selenium/testing.html");
    
      // Click on the textbox and send value
driver.findElement(By.cssSelector("input[id=fname]")).sendKeys("Selenium Tutorials");
     
    // Click on the Submit button using click() command
driver.findElement(By.cssSelector("button[id=idOfButton]")).click();
 
        
     // Close the Browser
             driver.close();
    
    }
}
    

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4