在Selenium中选择已知元素的父元素。
我们可以使用Selenium webdriver选择已知元素的父元素。首先,我们必须使用任何定位器(例如id、classname等)来识别已知元素。然后,我们必须使用**findElement(By.xpath())**方法识别其父元素。
我们可以通过使用子元素进行定位,然后将( ./..)作为参数传递给**findElement(By.xpath())**方法来识别其父元素。让我们在下面的HTML代码中,通过子元素的标签名li来识别其父元素的标签名ul。

我们还可以借助Javascript Executor来识别已知元素的父元素。我们必须将Javascript命令**return arguments[0].parentNode**和webelement作为参数传递给**executeScript**方法。Javascript中的**parentNode**命令用于指向元素的父元素。
示例
使用xpath的代码实现
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ParentElement{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://tutorialspoint.com/about/about_careers.htm");
// identify element
WebElement c=driver.findElement(By.xpath("//li[@class='heading']"));
//identify parent element with ./.. expression in xpath
WebElement p = c.findElement(By.xpath("./.."));
//getTagName to get tagname of parent
System.out.println("Parent tagname is: " + p.getTagName());
driver.close();
}
}使用Javascript Executor的代码实现。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ParentElementJS{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://tutorialspoint.com/about/about_careers.htm");
// identify element
WebElement c=driver.findElement(By.xpath("//li[@class='heading']"));
//identify parent element parentNode expression in Javascript command
WebElement p = (WebElement) ((JavascriptExecutor) driver).executeScript( "return arguments[0].parentNode;", c);
//getTagName to get tagname of parent
System.out.println("Parent tagname is: " + p.getTagName());
driver.close();
}
}输出

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP