我试图弄清楚XPath将检索' Love&浪漫'来自以下HTML
<div class="m-breadcrumbs no-mobile">
<a href="/home" class="breadcrumbs-link">Home</a><span class="delimiter_breadcrumb_spacer">></span>
<a href="/occasions/cat1000008">Occasions</a><span class="delimiter_breadcrumb_spacer">></span>
Love & Romance
</div>
我尝试过以下 Xpath
(//span[@class='delimiter_breadcrumb_spacer']/text()[last()])[2]
答案 0 :(得分:1)
提取文字爱情&amp;您提供的HTML中的Romance 可以使用下面代码块后面的executeScript()
方法( Java perspective ):
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()
方法作为替代方法:
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());