3

I am trying to navigate to the sibling <p> element using Selenium that has no id/class attributes. This is my HTML:

<div class="content1">              
    <div class="bold">                                              
        <a href="test">test</a>
    </div>
    <p>
        <span class="test two">Nuevo</span>
    </p>                                            

    <div class="bold2">  
        <a href="test">test</a>
    </div>
    <p>
        i want to get this text
    </p>
</div>

This is my selenium code:

element = driver.findElement(By.xpath("content1/p[2]"));

can anyone help me correct my selenium code?

3 Answers 3

2

Your XPath isn't valid in the first place. Did you mean .//div[@class='content1']/p[2]?

Please try

element = driver.findElement(By.xpath(".//div[@class='content1']/p[2]"));

Here is another XPath you can also have a try, which doesn't require indexing.

element = driver.findElement(By.xpath(".//div[@class='content1']/div[@class='bold2']/following-sibling::p"));

Note that if the HTML isn't the real one you are testing, you might face other issues, the above XPaths only provide the logic.

1
  • i think there is an automater at work.. PROBABLY with selenium. look at your rep. it has happened to myself, you, the other answerer and even the OP.
    – ddavison
    Commented Feb 19, 2014 at 21:34
1

Option #1 (assuming that these are the first <p> elements in the DOM):

element = driver.findElements(By.tagName("p")).get(1);

Option #2:

element = driver.findElement(By.xpath("//div[@class='content1']/p[2]"));
0
1

I've answered a question similar to this that could help you:

Selecting Nth-of-type in selenium

If you are interested in CSS, I'd check this out. If you are wondering on how to use CSS with selenium, check out this blog post: http://ddavison.github.io/css/2014/02/18/effective-css-selectors.html

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.