Home > Software design >  Use Selenium to extract span text content
Use Selenium to extract span text content

Time:12-08

can't figure out how to use selenium in python script to extract span text content: RSB - 12498 from the html shown. Please help. Thanks.

<div _ngcontent-pfw-c3="" style="visibility: visible; animation-name: fadeIn;"><figure _ngcontent-pfw-c3=""><a _ngcontent-pfw-c3="" href="detail-page.html"><img _ngcontent-pfw-c3="" alt="" src="http://via.placeholder.com/565x565.jpg"></a></figure><small _ngcontent-pfw-c3=""><!----><!----><span _ngcontent-pfw-c3=""> RSB - 12498</span>

CodePudding user response:

The locator to locate such span element will be //small/span if you want to use XPath.
CSS selector will be small span
So Selenium command to get such single element text will be:

goal = driver.find_element_by_css_selector('small span').text
print(goal)

Or

goal = driver.find_element_by_xpath('//small/span').text
print(goal)

In case there are multiple search results, the texts can be received from the list of resulted elements:

elements = driver.find_elements_by_css_selector('small span')
for element in elements:
    print(element.text)

Or

elements = driver.find_elements_by_xpath('//small/span')
for element in elements:
    print(element.text)
  • Related