Getting a child element with Selenium and Python

Question:

I have this HTML:

<div id = "d029384">
<span>......</span>
</div>

and my code:

elem = browser.find_elements_by_xpath("//div[contains(@id,'d')]")

except the div isn’t working for what my program is doing. I need to be more specific. I need the span element instead. How can I get the span element?
Each div has an id that is d + numbers. I need those numbers so that’s why I used that xpath but I don’t know how to make the final WebElement point to the span and not to the div.

Anyone know?

Asked By: Marcus Johnson

||

Answers:

Are you finding the right div? If so, to get the span inside that div, just add /span:

elem = browser.find_elements_by_xpath("//div[contains(@id,'d')]/span")
Answered By: unutbu

Or without using xpath, you can do (in case you have a single span in the div):

elem = browser.find_element_by_id("d029384").find_element_by_tag_name("span")
Answered By: Mercury
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.