Selenium get text from a table cell (td) with XPath

The element is <td>20175</td>

Xpath of the element is //*[@id="body"]/table/tbody/tr[1]/td/table[2]/tbody/tr/td[2]/table/tbody/tr[4]/td[1]

I want to take 20175 part.

I tried

  elems = browser.find_elements_by_xpath("""//*[@id="body"]/table/tbody/tr[1]/td/table[2]/tbody/tr/td[2]/table/tbody/tr[4]/td[1]""")

  print (elems)

But what it gave me this not the text.

selenium.webdriver.remote.webelement.WebElement (session="77dc0a7bef8dadbf9aec1ddbab9e3a91", element="0.027053967816755176-1")>]

Upvotes: 1

Views: 20095

Answers (1)

alecxe
alecxe

Reputation: 474231

What you see printed is a WebElement instance string representation. Instead, get the .text:

elem = browser.find_element_by_xpath("""//*[@id="body"]/table/tbody/tr[1]/td/table[2]/tbody/tr/td[2]/table/tbody/tr[4]/td[1]""")
print(elem.text)

Or, if there are multiple elements matching the locator:

elems = browser.find_elements_by_xpath("""//*[@id="body"]/table/tbody/tr[1]/td/table[2]/tbody/tr/td[2]/table/tbody/tr[4]/td[1]""")
print([elm.text for elm in elems])

Upvotes: 9

Related Questions