43

如何在没有 HTML 标签的情况下使用 selenium webdriver 获取网页的可见文本部分?

我需要与 Htmlunit 中的函数 HtmlPage.asText() 等效的东西。

使用函数 WebDriver.getSource 获取文本并使用 jsoup 解析它是不够的,因为页面中可能存在我对它们不感兴趣的隐藏元素(通过外部 CSS)。

4

3 回答 3

46

执行By.tagName("body")(或其他选择器以选择顶部元素),然后getText()对该元素执行将返回所有可见文本。

于 2013-08-20T14:57:56.850 回答
13

我可以帮助你使用 C# Selenium。

通过使用它,您可以选择该特定页面上的所有文本并将其保存到您首选位置的文本文件中。

确保你正在使用这些东西:

using System.IO;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;

到达特定页面后,尝试使用此代码。

IWebElement body = driver.FindElement(By.TagName("body"));
var result = driver.FindElement(By.TagName("body")).Text;

// Folder location
var dir = @"C:Textfile" + DateTime.Now.ToShortDateString();

// If the folder doesn't exist, create it
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);

// Creates a file copiedtext.txt with all the contents on the page.
File.AppendAllText(Path.Combine(dir, "Copiedtext.txt"), result);
于 2015-10-08T07:03:38.180 回答
7

我不确定您使用的是什么语言,但在 C# 中 IWebElement 对象有一个 .Text 方法。该方法显示元素的开始标签和结束标签之间显示的所有文本。

我会使用 XPath 创建一个 IWebElement 来抓取整个页面。换句话说,您正在抓取 body 元素并查看其中的文本。

string pageText = driver.FindElement(By.XPath("//html/body/")).Text;

如果上述代码不适用于 selenium,请使用以下代码:

string yourtext= driver.findElement(By.tagName("body")).getText();
于 2013-08-20T19:26:14.613 回答