如何从Selenium WebDriver,Java </h3>中的<h3>标签获取价值

时间:2012-08-10 13:41:31

标签: java selenium webdriver

我有HTML代码:

<div class="description">
<h3><strong>Samsung</strong> Galaxy SII (I9100)</h3>
<div class="phone_color"> ... </div>
...
</div>

我想从/ h3&gt;获取值 Samsung Galaxy SII(I9100)标签使用Selenium 2(WebDriver)

任何人都知道怎么做?

4 个答案:

答案 0 :(得分:3)

这是用C#编写的,但将它转换为Java应该不难:

/** Declare variables **/
string descriptionTextXPath = "//div[contains(@class, 'description')]/h3";

/** Find the element **/
IWebElement h3Element = driver.FindElement(By.XPath(descriptionTextXPath));

/** Grab the text **/
string descriptionText = h3Element.Text;

根据您是否有其他带有'description'类的div元素,您可能需要进一步微调您的结果。


以防万一:

为了找到页面上作为描述以供进一步使用的所有div,您可以这样做:

/** Declare XPath variable **/
string descriptionElementXPath = "//div[contains(@class, 'description')]";

/** Grab all description div elements **/
List<IWebElement> descriptionElements = driver.FindElements(By.XPath(descriptionElementXPath ));

然后,您可以使用forloop遍历每个元素并获取所需的数据。

以下是将上述C#代码转换为Java:

/ **声明变量** /

String descriptionTextXPath = "//div[contains(@class, 'description')]/h3";

/ **找到元素** /

IWebElement h3Element = driver.findElement(By.xpath(descriptionTextXPath));

/ **抓住文字** /

String descriptionText = h3Element.toString();

OR,

String descriptionText = h3Element.getText();

答案 1 :(得分:2)

WebElement divElement = driver.findelement(By.classname("description"));
String str = divElement.getText();
System.out.println(str);

这很完美.. 它帮了.. 谢谢:))

答案 2 :(得分:0)

WebElement divElement = driver.findelement(By.classname("description"));
String str = divElement.getText();
enter code here

str包含值。

答案 3 :(得分:0)

webDriver.findElement(By.tagName("h3"));