如何在Selenium WebDriver中获取Span标签的文本?

14

在Selenium Webdriver中,我如何从标签中提取文本并打印出来?

我需要提取文本UPS隔夜-免费

HTML代码如下:

div id="customSelect_3" class="select_wrapper">
<div class="select_display hovered">
<span class="selectLabel clear">UPS Overnight - Free</span>

使用以下代码:

String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span)).getText();
System.out.println(kk);

但是上面的代码返回/打印文本:1


谢谢大家提供的建议,但不幸的是,它们都没有得到预期的结果。仍然显示1作为结果。 - Onu
6
这段文字可见吗?我在使用Java时遇到了BR标签返回为空的问题。我使用了.getAttribute("innerHTML")代替.getText(),这将返回我想要的内容,包括任何隐藏的HTML或文本。 - jsherk
8个回答

17

也许span元素被隐藏了。如果是这种情况,则使用innerHtml属性:

By.css:

String kk = wd.findElement(By.cssSelector("#customSelect_3 span.selectLabel"))
              .getAttribute("innerHTML");

通过 XPath:

String kk = wd.findElement(By.xpath(
                   "//*[@id='customSelect_3']/.//span[contains(@class,'selectLabel')]"))
              .getAttribute("innerHTML");

"/.//" 的意思是 "在所选元素下面查找"。


1
谢谢,.getAttribute("innerHTML") 真的解决了我的问题。 - Rodolfo

6

我同意使用CSS更好。如果您确实想通过XPath实现,请尝试:

    String kk = wd.findElement(By.xpath(.//*div[@id='customSelect_3']/div/span[@class='selectLabel clear'].getText()))

3
你需要定位元素并使用getText()方法来提取文本。
WebElement element = driver.findElement(By.id("customSelect_3"));
System.out.println(element.getText());

3
您的代码应该这样写 -
String kk = wd.findElement(By.cssSelector("div[id^='customSelect'] span.selectLabel")).getText();

使用CSS。这样更加清洁、简单。如果这可以解决你的问题,请告诉我。


2
如果您更喜欢使用xpath,并且那个span是您的div下唯一的span,请使用我下面的示例。我建议使用CSS(请参见sircapsalot的帖子)。
String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']//span)).getText();

CSS示例:

String kk = wd.findElement(By.cssSelector("div[id='customSelect_3'] span[class='selectLabel clear']")).getText();

1
String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span));

kk.getText().toString();

System.out.println(+kk.getText().toString());

1
请提供需要翻译的英文内容。 - Alexander

0

从 span 标签获取文本的 PHP 方法:

$spanText = $this->webDriver->findElement(WebDriverBy::xpath("//*[@id='specInformation']/tbody/tr[2]/td[1]/span[1]"))->getText();

0

从 Span 标签中获取文本的 Pythonic 方式:

driver.find_element_by_xpath("//*[@id='customSelect_3']/.//span[contains(@class,'selectLabel clear')]").text

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接