Selenium教程

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

在本部分中,您将学习如何使用CSS-标签和ID选择器来定位特定的Web元素。
我们知道,定位特定的Web元素会涉及对其HTML代码的检查。
请按照以下步骤在示例Web页面上找到Textbox。
打开URL: https://www.testandquiz.com/selenium/testing.html 右键单击示例网页上的"文本框",然后选择"检查元素" 定位策略-通过CSS标签和ID 它将启动一个窗口,其中包含开发文本框所涉及的所有特定代码。 定位策略-通过CSS标签和ID 记下其Tag和其id属性的值。 定位策略-通过CSS标签和ID
Java语法通过CSS定位Web元素-标签和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选择器。我们在代码的每个部分都嵌入了注释,这些注释将指导您完成整个自动化过程。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class SampleOne {
    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#fname")).sendKeys("lidihuo");
     
    // Click on the Submit button using click() command
driver.findElement(By.cssSelector("button#idOfButton")).click();
 
        
     //  Close the Browser
             driver.close();
    
    }
}
    

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