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

use*_*328 5 java selenium webdriver

我有HTML代码:

<div class="description">
<h3><strong>Samsung</strong> Galaxy SII (I9100)</h3>
<div class="phone_color"> ... </div>
...
</div>
Run Code Online (Sandbox Code Playgroud)

我希望使用Selenium 2(WebDriver)从/ h3>标签获得三星Galaxy SII(I9100)的价值

谁知道怎么做?

Mic*_*sta 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;
Run Code Online (Sandbox Code Playgroud)

根据您是否有其他带有“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 ));
Run Code Online (Sandbox Code Playgroud)

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

以下是上述C#代码到Java的转换:

/** 声明变量 **/

String descriptionTextXPath = "//div[contains(@class, 'description')]/h3";
Run Code Online (Sandbox Code Playgroud)

/** 查找元素 **/

IWebElement h3Element = driver.findElement(By.xpath(descriptionTextXPath));
Run Code Online (Sandbox Code Playgroud)

/** 抓取文本 **/

String descriptionText = h3Element.toString();
Run Code Online (Sandbox Code Playgroud)

或者,

String descriptionText = h3Element.getText();
Run Code Online (Sandbox Code Playgroud)