Selenium Java: I want to access first div element inside a div class

余生长醉 提交于 2021-02-10 05:28:09

问题


Selenium Java: I want to access first div element inside a div class

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;

回答1:


You can you index of elements, so if you want to find out first div then just use div[1] at the end of xpath locator or if you want to get second div then div[2] and so on, like this:
WebElement element = driver.findElement(By.xpath("abc[1]"));

So, this will be answer for your question as per the give code:

WebElement element = driver.findElement(By.xpath("//div[@class='recommendation-header-social-container']/div[1]"));




回答2:


Using Xpath:

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

Or use css selector

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


来源:https://stackoverflow.com/questions/48591753/selenium-java-i-want-to-access-first-div-element-inside-a-div-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!