vb.net HtmlAgilityPack 获取页面标题和 H1 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14320026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 11:53:07  来源:igfitidea点击:

HtmlAgilityPack getting page title and H1 tags

vb.nettagsbrowserwebbrowser-controlhtml-agility-pack

提问by StealthRT

Hey all i am trying to get the page title and H1 tags from a webpage by doing the following

大家好,我正在尝试通过执行以下操作从网页中获取页面标题和 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

The only code above that works is the txtDescription part. Both the title and H1 do not. What type of syntax do i need to use in order to get those 2 tags?

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

The html code looks like this:

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

回答by jessehouwing

You can use doc.DocumentNode.SelectSingleNode("//head/title")and doc.DocumentNode.SelectNodes("//body//h1").

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

Or doc.DocumentNode.Descendants("title").SingleOrDefault()and doc.DocumentNode.Descendants("h1").

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