Home > Enterprise >  How to extract the text "152" from the textnode using Selenium
How to extract the text "152" from the textnode using Selenium

Time:04-04

enter image description here

I need to extract the xpath for the number 152. The xpath that I created extracts the text after 152 which is "Test" but excludes the number 152. I need to get this count.

I am using below xpath :

//div\[@class='filter_filter__5H_fi'\]/h1

Not sure how to get this.

CodePudding user response:

As per the HTML:

HTML

both the text 152 and Test are within their respective text nodes.


Solution

To retrive the text 152 you can use either of the following locator strategies:

  • Using Java, cssSelector and firstChild:

    WebElement = driver.findElement(By.cssSelector("div.filter_filter__5H_fi > h1"));
    System.out.println(((JavaScriptExecutor)driver).executeScript("return arguments[0].firstChild.textContent;", element).toString());
    
  • Using Python, xpath and firstChild:

    parent_element = driver.find_element(By.XPATH, "//div[@class='filter_filter__5H_fi']/h1")
    print(driver.execute_script('return arguments[0].firstChild.textContent;', parent_element).strip())
    
  • Related