这是用 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;
根据您是否有其他具有“描述”类的 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();
或,
String descriptionText = h3Element.getText();