How to get WebElement text with selenium

前端 未结 2 1823
心在旅途
心在旅途 2021-01-18 05:56

Please see the following element:

User \'M
相关标签:
2条回答
  • 2021-01-18 06:33
    WebElement element = driver.findElement(By.className("div.success")
    element.getText();
    

    shall help you get the text of the div

    0 讨论(0)
  • 2021-01-18 06:49

    The text you want is present in a text node and cannot be retrieved directly with Selenium since it only supports element nodes.

    You could remove the beginning :

    String buttonText = driver.findElement(By.cssSelector("div.success > button")).getText();
    String fullText = driver.findElement(By.cssSelector("div.success")).getText();
    String text = fullText.substring(buttonText.length());
    

    You could also extract the desired content from the innerHTML with a regular expression:

    String innerText = driver.findElement(By.cssSelector("div.success")).getAttribute("innerHTML");
    String text = innerText.replaceFirst(".+?</button>([^>]+).*", "$1").trim();
    

    Or with a piece of JavaScript:

    String text = (String)((JavascriptExecutor)driver).executeScript(
        "return document.querySelector('div.success > button').nextSibling.textContent;");
    
    0 讨论(0)
提交回复
热议问题