0

The structure that I am looking at is the following

<div id="historyContainer">
    <div class id="offerHistory">
        <div class="theTitle">…</div>
        <br>
        <p>…</p>
        <br>
        <h3>Title</h3>
    </div>
</div>

Here is my Python

offerHistory = browser.find_element_by_id('offerHistory')
title = offerHistory.find_elements_by_tag_name('h3')
print(title)

This is what prints

[<selenium.webdriver.remote.webelement.WebElement (session="d7aef4eab17ec32e0280c1177b5016d9", element="eaf8e28e-9620-4e94-81a8-f7e13edc2c48")>]

How do I print 'Title'?

Guy
  • 34,831
  • 9
  • 31
  • 66
letsCode
  • 2,572
  • 1
  • 6
  • 27
  • 1
    Does this answer your question? [Python and how to get text from Selenium element WebElement object?](https://stackoverflow.com/questions/28022764/python-and-how-to-get-text-from-selenium-element-webelement-object) – Chris L. Mar 03 '20 at 14:38
  • 1
    The return value is a list, so if you only want the first one (because you know you only have one): `print(title[0].text)` should work – ChatterOne Mar 03 '20 at 14:46
  • @chatterone I get a index out of bounds – letsCode Mar 03 '20 at 14:53
  • If you get index out of bounds, then that output is not what you get, because it shows a list `[]` – ChatterOne Mar 03 '20 at 14:58

2 Answers2

0

Add ".text":

title = browser.find_elements_by_tag_name('h3')
print(title.text)
zvi
  • 2,593
  • 20
  • 33
0

You were close. Within the <div class id="offerHistory"> parent node:

<div class id="offerHistory">
    <div class="theTitle">…</div>
    <br>
    <p>…</p>
    <br>
    <h3>Title</h3>
</div>

There is only one <h3> tag which is correctly returned by:

title = offerHistory.find_elements_by_tag_name('h3')

So when you print(title) the element is printed as:

[<selenium.webdriver.remote.webelement.WebElement (session="d7aef4eab17ec32e0280c1177b5016d9", element="eaf8e28e-9620-4e94-81a8-f7e13edc2c48")>]

In your usecase you are looking to extract the text Title from the <h3> node and you can use either of the following Locator Strategies:

  • Using css_selector and get_attribute():

    print(driver.find_element_by_css_selector("div#offerHistory h3").get_attribute("innerHTML"))
    
  • Using xpath and text attribute:

    print(driver.find_element_by_xpath("//div[@id='offerHistory']//h3").text)
    
DebanjanB
  • 118,661
  • 30
  • 168
  • 217