driver.findElements(By.xpath( "//div[contains(@class, 'f nsa _uQb')]" ))的结果错误;


driver.get("https://www.google.co.in/webhp?
                     hl=en#hl=en&tbm=nws&q=site+:+www.google.com");
java.util.List<WebElement> dates = driver.findElements(
                     By.xpath("//div[contains(@class, 'f nsa _uQb')]"));
 System.out.println(dates.size());

正在尝试上面的代码...我得到的是输出zero,而不是它应该是什么,10.

如果我做错了什么,请建议...

嗨,

请找到答案

public class FetchDate {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        WebDriver driver = new FirefoxDriver();
        driver .get("https://www.google.co.in/webhp?hl=en#hl=en&tbm=nws&q=site+:+www.google.com");
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        List<WebElement> dates = driver.findElements(By.cssSelector(".f.nsa._uQb"));
        // for finding size 
        System.out.println(dates.size());
        // for printing every date 
        for(WebElement Dates : dates){
            System.out.println("date for the search is : " + Dates.getText());
        }

更新:

// for printing the way you want do it like below 
List<WebElement> dates = driver.findElements(By.cssSelector(".f.nsa._uQb"));
     for (int j = 0; j < dates.size(); j++) {
                String date = dates.get(j).getText(); 
                System.out.println(date);
            }
            }
    }

输出为:

10
date for the search is : 29-Apr-2016
date for the search is : 03-May-2016
date for the search is : 29-Apr-2016
date for the search is : 20-Apr-2016
date for the search is : 16-Apr-2016
date for the search is : 30-Apr-2016
date for the search is : 25-Apr-2016
date for the search is : 25-Apr-2016
date for the search is : 21-Apr-2016
date for the search is : 07-Apr-2016

你的构造方式是错误的 xpath 试试这个,

/

/*[contains(concat(' ', @class, ' '(, ' f nsa _uQb '(]

java.util.list dates = driver.findElements( By.xpath("//*[contains(concat(' ', @class, ' '(, ' f nsa _uQb '(]"((;

注意空格

日期在 <span> 标签中,而不是<div> 。尝试

List<WebElement> dates = driver.findElements(By.xpath("//span[contains(@class, 'f nsa _uQb')]"));

您还可以按nsa_uQb类查找日期

List<WebElement> dates = driver.findElements(By.className("nsa"));
List<WebElement> dates = driver.findElements(By.className("_uQb"));

最新更新