【问题标题】:HtmlAgilityPack getting page title and H1 tagsHtmlAgilityPack 获取页面标题和 H1 标签
【发布时间】:2012-12-28 12:09:00
【问题描述】:

嘿,我正在尝试通过执行以下操作从网页中获取页面标题和 H1 标签

    doc.LoadHtml(htmlSourceCode)

    txtTitle.Text = doc.GetElementsByTagName("title").InnerText()

    txtH1.Text = doc.GetElementsByTagName("H1").InnerText()

    For Each channel In doc.DocumentNode.SelectNodes(".//meta[@name='description']")
        txtDescription.Text = channel.Attributes("content").Value
    Next

上面唯一有效的代码是 txtDescription 部分。标题和 H1 都没有。为了获得这 2 个标签,我需要使用什么类型的语法?

html 代码如下所示:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html;charset=utf-8" /><title>
    The title text is here!
</title><link rel="icon" type="image/x-icon" href="http://www.zzzz.com/favicon.ico" />
....
<div class="main-content">
    <div class="block-info">
        <div class="container">
            <div class="article">
                <h1>
                    This is the H1 tag with the text!</h1>

<p>As the 2nd held tru

【问题讨论】:

  • 你试过doc.DocumentNode.GetElementsByTagName而不是doc.GetElementsByTagName吗?
  • @Oded 我在“HtmlNode”类型上找不到公共成员“GetElementsByTagName”。 这样做时。
  • 您使用的是什么版本的 HAP?我在HtmlDocumentDocumentNode 上都没有看到GetElementsByTagName
  • 您使用的是 WebBrowser 控件还是 Html Agility Pack?你的标签建议两者,但这可能不是真的。
  • @jessehouwing 是的,两者都是。 webbrowser 获取 htmlSourceCode 然后 Html Agility Pack 来解析我需要的内容。

标签: vb.net tags browser webbrowser-control html-agility-pack


【解决方案1】:

您可以使用doc.DocumentNode.SelectSingleNode("//head/title")doc.DocumentNode.SelectNodes("//body//h1")

或者doc.DocumentNode.Descendants("title").SingleOrDefault()doc.DocumentNode.Descendants("h1")

【讨论】:

  • 我也收到错误:找不到类型“HtmlDocument”上的公共成员“DocumumentNode”。使用 txtTitle.Text = doc.DocumumentNode.SelectSingleNode("/ /head/title")Method not found: 'Int32 System.Environment.get_CurrentManagedThreadId()'。 对于 txtTitle.Text = doc.DocumentNode.Descendants("title ").SingleOrDefault()
  • 您确定您使用的是 HtmlAgilityPack 吗?这些方法调用是在HtmlAgilityPack.HtmlDocument 上进行的。
  • 有一个错字... DocumumentNode 应该是 DocumentNode
猜你喜欢
  • 2011-05-04
  • 2013-12-25
  • 2018-09-08
  • 2018-01-05
  • 1970-01-01
  • 2013-06-02
  • 2011-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多