Search code examples
pythonseleniumweb-scrapingxpathhtml-parsing

Python Selenium search for sibbling [object Text] that only have a text


I want to get the text of an expression in xpath that only has text in its sibling html_code

I'm trying this way but it gives me an error and I don't know how to select the text, since it doesn't have any tag


driver.find_element('xpath','//li[@class="icon-feature"]//i[@class="icon-stotal"]//following-sibling::text()').text

Error:

InvalidSelectorException: invalid selector: The result of the xpath expression "//li[@class="icon-feature"]//i[@class="icon-stotal"]//following-sibling::text()" is: [object Text]. It should be an element.

I want to have only " 121 m2 Total" with this.

Any help on this is appreciated.


Solution

  • find_element must return a webelement, and you cannot convert a text node into a webelement.

    In general to get text not wrapped in any tags, you must get the text of the parent and remove from it the text of the children. In this case there is only one child so

    child  = driver.find_element(By.XPATH, "//i[@class='icon-stotal']")
    parent = driver.find_element(By.XPATH, "//i[@class='icon-stotal']/parent::li")
    

    Then

    >>> parent.text.replace(child.text,'')
    ' 121 m total'