简体   繁体   中英

How to read the html tags innerHTML value using css selector or xpath.?

My actual query is, I want to retrieve the HTML inner text value using css selector or xpath. I am able to acheive this by using document.getElementById but not using selectors, instead I can only able to print the tag element but not the text from it.

For Ex:

<li class="active">
  <span id="lastPrice">1,603.35</span>
  &nbsp;&nbsp;<span id="CAToday"></span><br>
  <span class="up" id="change">28.80</span>
</li>

From the above HTML, I want to print 1,603.35 using either

  • Css or

  • xpath

Note: I have drilled the forum already but couldn't able to find required solution.

This XPath expression

string(/li/span[@id='lastPrice'])

With this well-formed XML

<li class="active">
  <span id="lastPrice">1,603.35</span>
  <span id="CAToday"></span><br/>
  <span class="up" id="change">28.80</span>
</li>

Result

1,603.35

Check in http://www.utilities-online.info/xpath/?save=07d6e884-4f7e-46cc-9aaf-904e6a440f50-xpath

You should be able to use the XPath version 2 matches function:

//div[matches(text(), 'Hello ?\w+ What would you like to do today \w+')]

which does allow regular expressions.

Java Selenium (xpath example):

driver.findElement(By.xpath("//span[@id='lastPrice']").getAttribute("innerText")

Python Selenium (CSS example):

driver.find_element_by_css_selector("span#lastPrice").get_attribute("innerText")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM