Java+Selenium3方法篇8-findElement之By ClassName


本文继续介绍WebDriver关于元素定位系列方法,这篇介绍By ClassName。看到ClassName,LinkText,XPath,ID这些方法,所以说,要做好Web自动化测试,最好是需要了解一些前端的基本知识。有了前端知识,做元素定位会很轻松,同样写网络爬虫也很有帮助,话题扯远了,回到Selenium自动化测试。如何查找元素的ClassName,还是那句话,没有前端知识,就回到我之前写的如何XPath入门那篇文章,利用firepath可以很容易得到元素的ClassName,获取你在浏览器按下F12,也可以,但是没有firepath方便。

下面还是通过百度首页举例,采用classname定位搜索输入框和百度一下这个按钮,其中定位百度一下会报错。

  1. package lessons;  
  2.   
  3. import java.util.concurrent.TimeUnit;  
  4.   
  5. import org.openqa.selenium.By;  
  6. import org.openqa.selenium.WebDriver;  
  7. import org.openqa.selenium.chrome.ChromeDriver;  
  8.   
  9.     
  10. public class ByClassName {    
  11.     
  12.     public static void main(String[] args) throws Exception {    
  13.             
  14.         System.setProperty("webdriver.chrome.driver"".\\Tools\\chromedriver.exe");    
  15.              
  16.         WebDriver driver = new ChromeDriver();    
  17.        
  18.         driver.manage().window().maximize();    
  19.          
  20.         driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);  
  21.             
  22.         driver.get("https://www.baidu.com");    
  23.           
  24.         driver.findElement(By.className("s_ipt")).sendKeys("Java");  
  25.           
  26.         driver.findElement(By.className("bg s_btn_wr")).click();  
  27.     }  
  28. }  
package lessons;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

  
public class ByClassName {  
  
    public static void main(String[] args) throws Exception {  
          
        System.setProperty("webdriver.chrome.driver", ".\\Tools\\chromedriver.exe");  
           
        WebDriver driver = new ChromeDriver();  
     
        driver.manage().window().maximize();  
       
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
          
        driver.get("https://www.baidu.com");  
        
        driver.findElement(By.className("s_ipt")).sendKeys("Java");
        
        driver.findElement(By.className("bg s_btn_wr")).click();
    }
}
报错内容核心原因如下。

  1. <span style="color: rgb(255, 0, 0);">Exception in thread "main" org.openqa.selenium.InvalidSelectorException: invalid selector: Compound class names not permitted</span>  
Exception in thread "main" org.openqa.selenium.InvalidSelectorException: invalid selector: Compound class names not permitted
       根据代码报错和脚本测试回放,发现在定义文本输入框是没有问题,但是在定位百度一下这个按钮就出问题。报错提示告诉了我们原因:无效的selector,不允许组合的class name。根本原因是这个className "bg s_btn_wr"有空格,所以,以后遇到classname有空格的,就换成别的定位元素方法。这里解释下selector的意思,有时候有些文章或说localtor,特别是Selenium for Python就会说localtor,localtor就像我们寄快递的地址一样。这里localtor = By + 各种方法对应的值。By我们知道有8中方法,所有对应有八种值,这里值就是错误信息中提到的selector,明白了吧。

猜你喜欢

转载自blog.csdn.net/bnuyangwu/article/details/80761590