Text1 Text2 ...">

Extract text from inner tag in Selenium

Here's a snippet of HTML:

<label class="abc">
  <span class="bcd">Text1</span>
  Text2
</label>

      

How to simply extract Text2

using selenium script? I know how to extract Text2

by getting innerHTML

the "abc" innerHTML

class and then removing the "bcd" class. But I'm just looking for the best way to solve this problem.

+3
java html selenium


source to share


3 answers


Try the following:



WebElement element = driver.findElement(By.xpath("//label[contains(text(),'Text2')]"));
String test = element.getText();

      

0


source to share


XPath:

//label[@class='abc']/child::text()

      

for Python:



returnText = driver.execute_script("return document.evaluate(\"//label[@class='abc']/child::text()\", document, null, XPathResult.STRING_TYPE, null).stringValue;")

      

sometimes, there may be spaces and it is evaluated as a string by the program, so you must use an array:

    returnText = []
    returnText = self.driver.execute_script("var iterator = document.evaluate(\"//label[@class='abc']/child::text()\", document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); var arrayXpath = new Array();  var thisNode = iterator.iterateNext(); while (thisNode) {arrayXpath.push(thisNode.textContent);  thisNode = iterator.iterateNext(); }    return arrayXpath;")

    for item in returnText:
        print item

      

0


source to share


Try the following:

String text2=driver.findElement(By.xpath("//label[@class='abc']").Text;

      

-1


source to share







All Articles