如何在Span中获取文本

时间:2018-05-15 09:34:29

标签: selenium xpath

我试图弄清楚XPath将检索' Love&浪漫'来自以下HTML

<div class="m-breadcrumbs no-mobile">
   <a href="/home" class="breadcrumbs-link">Home</a><span class="delimiter_breadcrumb_spacer">&gt;</span>
   <a href="/occasions/cat1000008">Occasions</a><span class="delimiter_breadcrumb_spacer">&gt;</span>
   Love &amp; Romance
</div>

我尝试过以下 Xpath

(//span[@class='delimiter_breadcrumb_spacer']/text()[last()])[2]

3 个答案:

答案 0 :(得分:1)

提取文字爱情&amp;您提供的HTML中的Romance 可以使用下面代码块后面的executeScript()方法( Java perspective ):

  • executeScript()

    WebElement myElement = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='m-breadcrumbs no-mobile']")));
    String myText = ((JavascriptExecutor)driver).executeScript('return arguments[0].lastChild.textContent;', myElement).strip()
    

更新

提取文字爱情&amp;浪漫您还可以使用 Java的 split()方法作为替代方法:

  • split()

    WebElement myElement = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='m-breadcrumbs no-mobile']")));
    String my_string = myElement.getAttribute("innerHTML");
    String[] stringParts = my_string.split("\n");
    String mypart = stringParts[5];
    System.out.println(mypart);
    

答案 1 :(得分:1)

尝试使用以下代码获取所需的文本节点:

WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div.m-breadcrumbs.no-mobile")));
JavascriptExecutor jse = (JavascriptExecutor)driver;
String loveRomance = jse.executeScript("return arguments[0].lastChild.textContent;", myDynamicElement);

答案 2 :(得分:0)

您可以从div中删除所有子项并使用该div。

WebElement a = driver.findElement(By.xpath("//div[@class='m-breadcrumbs no-mobile']"));
List<WebElement> b = a.findElements(By.xpath("./*"));

for(WebElement aux : b) {

    JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
    jsExecutor.executeScript("arguments[0].parentNode.removeChild(arguments[0])", aux);

}

System.out.println(a.getText());