1

次のコードを使用して、ページからすべてのテキストをList<string>

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(content);

foreach (var script in doc.DocumentNode.Descendants("script").ToArray())
    script.Remove();

foreach (var style in doc.DocumentNode.Descendants("style").ToArray())
    style.Remove();

foreach (HtmlAgilityPack.HtmlNode node in doc.DocumentNode.SelectNodes("//text()"))
{
    string found = WebUtility.HtmlDecode(node.InnerText.Trim());
    if (found.Length > 2) // removes some unwanted strings
        query[item.Key].Add(found);
}
  • しかし、このコードを絞り込むためのより良い方法があるなど、一部のhtmlはまだ文字列に含まれて</form>いるため、各タグのテキストのみを取得し、他には何も取得しません。または、結果を解析して<*>タグを削除する必要がありますか?
4

1 に答える 1

5

これは、HAP に含まれる関数のみを使用して、かなり簡単に実行できます。

HtmlDocument doc = new HtmlWeb().Load("http://www.google.com");
List<string> words = doc.DocumentNode.DescendantNodes()
        .Where(n => n.NodeType == HtmlNodeType.Text
          && !string.IsNullOrWhiteSpace(HtmlEntity.DeEntitize(n.InnerText))
          && n.ParentNode.Name != "style" && n.ParentNode.Name != "script")
        .Select(n => HtmlEntity.DeEntitize(n.InnerText).Trim())
        .Where(s => s.Length > 2).ToList();

結果は、長さが 2 を超える単語のリストであり、すべてが既にエスケープされているため、WebUtility.

于 2012-05-30T21:10:27.150 に答える