Selenium Java:我想访问div类中的第一个div元素

时间:2018-02-02 22:26:27

标签: selenium-webdriver

Selenium Java:我想访问div类中的第一个div元素

public int checkLinks()
    {

int x = driver.findElements(By.xpath("//div[@class='recommendation-header-social-container']/div")).size();
        List<WebElement> y = driver.findElements(By.xpath("//div[@class='recommendation-header-social-container']/div"));
        int i=0;
        for(WebElement element:y)
        {       
        String btn=element.findElement(By.xpath("//div[@class='recommendation-header-social-container']")).getAttribute("innerHTML");
            System.out.println("Length of first element: "+btn.length());

        }
            return x;

2 个答案:

答案 0 :(得分:0)

使用Xpath:

String btn=element.findElement(By.xpath("(//div[@class='recommendation-header-social-container'])[1]")).getAttribute("innerHTML");

或使用css选择器

driver.findElement(By.cssSelector("div.recommendation-header-social-container > div:nth-child(1)"));

答案 1 :(得分:0)

你可以索引元素,所以如果你想找出第一个div ,那么只需在xpath定位器的末尾使用 div [1] ,或者你想要获得第二个div 然后 div [2] 等等,如下所示:
WebElement element = driver.findElement(By.xpath(&#34; abc [1]&#34;));

因此,根据给定代码,这将是您的问题的答案:

WebElement element = driver.findElement(By.xpath(&#34; // div [@class =&#39; recommendation-header-social-container&#39;] / div [1]&#34;)); < / p>