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

Selenium webdriver SeleniumJava:我想访问div类中的第一个div元素,selenium-webdriver,Selenium Webdriver,SeleniumJava:我想访问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='

SeleniumJava:我想访问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;
public int checkLinks()
{
int x=driver.findElements(By.xpath(“//div[@class='recommunication-header-social-container']/div”).size();
List y=driver.findElements(By.xpath(“//div[@class='recommunication-header-social-container']/div”);
int i=0;
for(WebElement:y)
{       
字符串btn=element.findElement(By.xpath(“//div[@class='recommunication-header-social-container'])).getAttribute(“innerHTML”);
System.out.println(“第一个元素的长度:+btn.Length());
}
返回x;
使用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)"));

您可以对元素进行索引,因此如果您想找到第一个div,那么只需在xpath定位器的末尾使用div[1],或者如果您想获得第二个div然后div[2]等等,如下所示:
WebElement=driver.findElement(By.xpath(“abc[1]”)

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


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

尝试了这个解决方案,但得到了与没有div时相同的输出对不起,我想我在编写代码时输入了错,最后尝试“div[1]”而不是“div[0]”(我在回答中也更正了它)。如果它不起作用,那么您能告诉我,根据您上面给定的代码,x的值是多少吗?即使我给出div[1],它也会给出“NoTouchElementException”哦,如果不查看该页面的html,就很难说出确切的答案,您可能需要检查“IFRAME”标记中是否存在此定位器。否则,您可以在此处添加该页面的完整html,以便我们可以调试此问题。