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

时间:2016-05-05 05:48:24

标签: selenium selenium-webdriver

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

请建议我做错了什么......

3 个答案:

答案 0 :(得分:0)

您好,请找到答案

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

答案 1 :(得分:0)

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

// * [contains(concat(&#39;&#39;,@ class,&#39;&#39;),&#39; f nsa _uQb&#39;)] < /强>

  

java.util.List dates = driver.findElements(                        By.xpath(&#34; // * [contains(concat(&#39;&#39;,@ class,&#39;&#39;),&#39; f nsa _uQb&#39;) ]&#34));

请注意空格

答案 2 :(得分:0)

日期位于<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"));