Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a child element with Selenium and Python

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?

like image 353
Marcus Johnson Avatar asked Sep 29 '13 21:09

Marcus Johnson


People also ask

How do you get child elements in Selenium?

We can locate child nodes of web elements with Selenium webdriver. First of all we need to identify the parent element with help of any of the locators like id, class, name, xpath or css. Then we have to identify the children with the findElements(By. xpath()) method.

How do you fetch an attribute value of an element in Selenium?

We can get the attribute of element in Selenium webdriver. The getAttribute() method is used to obtain the value of an attribute in an html document. In an html code, attribute and its value appear as a key value pair. Some of the commonly known html attributes are disabled, alt, id, href, style, title and src.

Can you use Python with Selenium Webdriver?

Selenium is an open source automation testing tool that supports a number of scripting languages like Python, C#, Java, Perl, Ruby, JavaScript, etc.


2 Answers

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")
like image 180
Mercury Avatar answered Oct 19 '22 18:10

Mercury


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")
like image 35
unutbu Avatar answered Oct 19 '22 18:10

unutbu