问题
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