Get some text with java + selenium WebDriver

后端 未结 4 1558
深忆病人
深忆病人 2020-12-12 02:08

I want to get only the text \"Invitation sent to xxxxx\", I do not want to get what\'s inside the

相关标签:
4条回答
  • 2020-12-12 02:25

    Given the HTML, you should be able to .getText(), split that text on a newline, and then take the first split to get the text you want.

    driver.findElement(By.cssSelector("p.artdeco-toast-message")).getText().split("\r\n")[0];
    
    0 讨论(0)
  • 2020-12-12 02:36

    You can try with the following code.

    WebElement text=driver.findElement(By.className("artdeco-toast-message"));
    String wholeText = text.getText();
    String unWantedText=text.findElement(By.className("action")).getText();
    String RequiredText=wholeText.replace(unWantedText,"");
    System.out.println(RequiredText);
    
    0 讨论(0)
  • 2020-12-12 02:43

    In fact Selenium's getText() method retrieves all the text in sub elements too, so the approach, recommended by Murthi is the most applicable, as far as I know. Try this approach:

    String newLine = System.getProperty("line.separator");
    String pessoapopu = driver.findElement(By.className("artdeco-toast-message"))
                               .getText().replaceAll(newLine, "");
    

    Or try/ask for more convenient HTML code.

    0 讨论(0)
  • 2020-12-12 02:43

    You can use //p[@class='artdeco-toast-message']/text() xpath to locate the Invitation sent to xxxxx text but selenium doesn't support text() method in xpath to locate a text node.

    Either if you try to locate the element using below xpath to exclude the button text by using not() function of xpath :

    //p[@class='artdeco-toast-message']/node()[not(self::button)]
    

    Again it locating the element using text node so Selenium doesn't allow this

    Here one solution available to execute same xpath i.e. JavascriptExecutor

    Use evaluate() method of JavaScript and evaluate your xpath using JavascriptExecutor

    JavascriptExecutor js = (JavascriptExecutor)driver;
    Object message = js.executeScript("var value = document.evaluate(\"//p[@class='artdeco-toast-message']/text()\",document, null, XPathResult.STRING_TYPE, null ); return value.stringValue;");
    System.out.println(message.toString().trim());
    

    OR

    JavascriptExecutor js = (JavascriptExecutor)driver;
    Object message = js.executeScript("var value = document.evaluate(\"//p[@class='artdeco-toast-message']/node()[not(self::button)]\",document, null, XPathResult.STRING_TYPE, null ); return value.stringValue;");
    System.out.println(message.toString().trim());
    

    It will give you the expected result. No need to get all data and then formatting using String functions.

    You can explore evaluate() in detail from here

    0 讨论(0)
提交回复
热议问题