Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

I am trying to search for an element in a sub-element with Selenium (Version 2.28.0), but selenium do not seem to limit its search to the sub-element. Am I doing this wrong or is there a way to use element. find to search a sub-element?

For example, I created a simple test webpage with this code:

<!DOCTYPE html>

<html>

    <body>

        <div class=div title=div1>

            <h1>My First Heading</h1>

            <p class='test'>My first paragraph.</p>

        </div>

        <div class=div title=div2>

            <h1>My Second Heading</h1>

            <p class='test'>My second paragraph.</p>

        </div>

        <div class=div title=div3>

            <h1>My Third Heading</h1>

            <p class='test'>My third paragraph.</p>

        </div>

    </body>

</html>

My python (Version 2.6) code looks like this:

from selenium import webdriver

driver = webdriver.Firefox()

# Open the test page with this instance of Firefox

# element2 gets the second division as a web element

element2 = driver.find_element_by_xpath("//div[@title='div2']")

# Search second division for a paragraph with a class of 'test' and print the content

print element2.find_element_by_xpath("//p[@class='test']").text 

# expected output: "My second paragraph."

# actual output: "My first paragraph."

If I run:

print element2.get_attribute('innerHTML')

It returns the HTML from the second division. So selenium is not limiting its search to element2.

I would like to be able to find a sub-element of element2. This post suggests my code should work Selenium WebDriver access a sub element but his problem was caused by a time-out issue.

Can anyone help me understand what is happening here?

1 Answer

0 votes
by (62.9k points)

When you start your XPath expression with //, it searches from the root of the document ignoring your parent element. You should prepend the expression as shown below.

element2 = driver.find_element_by_xpath("//div[@title='div2']")

element2.find_element_by_xpath(".//p[@class='test']").text 

Hope this helps!

If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, check out Intellipaat’s Selenium automation course!

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...