Skip to content

Examples for XPath selector

Sushil Kumar Gupta edited this page Feb 6, 2022 · 3 revisions

Note:

  • 🟩 //div[@id='container']//h2[text()='Inside Shadow DOM'] is correct
  • 🟩 //div[@id='container']/h2[text()='Inside Shadow DOM'] is correct
  • 🟩 For examples on XPath follow the link

Pages with Shadow DOM:

Download all the files and put them in a single directory.

Use LocalFileTest to test all the XPath scenarios.

I am writing some of the examples from this class.

@Test
public void testXPathWithIndex() {
	driver.navigate().to(getPageContent("index.html"));
	WebElement element = shadow.findElementByXPath("//body//div[1]");
	assertThat(element, notNullValue());
}

@Test
public void testXPathWithText() {
	driver.navigate().to(getPageContent("index.html"));
	WebElement element = shadow.findElementByXPath("//h3[text()='some DOM element']");
	assertThat(element, notNullValue());
}

@Test
public void testXPathWithTextInsideShadow() {
	driver.navigate().to(getPageContent("index.html"));
	WebElement element = shadow.findElementByXPath("//div[@id='container']//h2[text()='Inside Shadow DOM']");
	assertThat(element, notNullValue());
}

@Test
public void testAllElementsXPath() {
	driver.navigate().to(getPageContent("index.html"));
	WebElement element = shadow.findElementByXPath("//div[@id='container']//h2[text()='Inside Shadow DOM']");
	assertThat(element, notNullValue());
}

@Test
public void testAllElementsXPathWithText() {
	driver.navigate().to(getPageContent("index.html"));
	List<WebElement> element = shadow.findElementsByXPath("//div[@id='container']//h2[text()='Inside Shadow DOM']");
	assert element.size()==2;
}

@Test
public void testAllElementsXPathWithId() {
	driver.navigate().to(getPageContent("index.html"));
	List<WebElement> element = shadow.findElementsByXPath("//div[@id='container']//h2[@id='inside']");
	assert element.size()==2;
}