2

I have this HTML

<tr height="22px">
    <td colspan="1" class="det" width="40%">Net Sales</td>

    <td align="right" class="det">2,548.00</td>
    <td align="right" class="det">1,946.36</td>
    <td align="right" class="det">1,139.14</td>
    <td align="right" class="det">2,345.60</td>
    <td align="right" class="det">1,323.84</td>
</tr>

I find the element using text:

from selenium import webdriver
driver = webdriver.Chrome()
driver.get("url")

quarterly_results_data = driver.find_element_by_xpath("//*   [contains(text(),'Net Sales)]")

print(quarterly_results_data.text)

I get:

Net Sales

However I want all the text between parent <tr>:

Net Sales
2,548
1,946
...

Using :

print(quarterly_results_data.parent.text)

does not give any results.

I know it can be done by beautifulsoup, but I will have to use html parser every time i click on a new link. Please help with the right syntax.

1
  • Please take a minute to fix the indent and spacing in the HTML so that it's easier to read. Commented Feb 25, 2017 at 15:04

1 Answer 1

2

You should get text of parent element as below:

quarterly_results_data = driver.find_element_by_xpath("//*[contains(text(),'Net Sales')]/parent::*")
print(quarterly_results_data.text)

or

quarterly_results_data = driver.find_element_by_xpath("//tr[td[text()='Net Sales']]")
print(quarterly_results_data.text)

If you need to print out each td value separately:

for child in quarterly_results_data.find_elements_by_xpath('./td'):
    print(child.text)
Sign up to request clarification or add additional context in comments.

1 Comment

The question is about how to get all child nodes text. Why are you writing about parent nodes?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.