roger_that
roger_that

Reputation: 9791

Unable to read <p> text under <h3> using selenium

I have an html code something like:

<h3> Some Heading </h3>
<p> Some String </p>
<p> more string </p>
<h3> Other heading</h3>
<p> some text </p>

I am trying to access Some String, more string and some text. With java, am trying to access like this:

List<WebElement> h3Tags = driver.findElements(By.tagName("h3"));

List<WebElement> para = null;

WebElement bagInfo = h3Tags.get(0);  //reads first h3
if(bagInfo.getText().contains("carry-on") || bagInfo.getText().contains("Carry-on")){
        para = AutoUtils.findElementsByTagName(bagInfo, "p");
        System.out.println(para.get(0).getText());  //Null pointer here 
}

bagInfo = h3Tags.get(1);
if(bagInfo.getText().contains("checked") || bagInfo.getText().contains("Checked")){
        para = AutoUtils.findElementsByTagName(bagInfo, "p");
        System.out.println(para.get(0).getText());  //Null pointer here too
}

Tried xpath like "h3['/p']" but still no luck. What is the best way to access those <p> strings?

Upvotes: 0

Views: 500

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193108

To access Some String, more string and some text you can use the following Locator Strategy :

  • To access the node with text as Some String

    By.xpath("//h3[normalize-space()='Some Heading']//following::p[1]")
    
  • To access the node with text as more string

    By.xpath("//h3[normalize-space()='Some Heading']//following::p[2]")
    
  • To access the node with text as some text

    By.xpath("//h3[normalize-space()='Other heading']//following::p[1]")
    
  • Once you locate those elements you can use getAttribute("innerHTML") method to extract the text within the nodes.

Upvotes: 0

Andersson
Andersson

Reputation: 52665

Try xpath //h3/following-sibling::p to match all 3 paragraphs

Also note that your XPath h3['/p'] doesn't work as it means return h3 node which is DOM root node. Predicate ['/p'] will always return True as non-empty string ('/p' in your case) is always True

Upvotes: 2

Related Questions