本文介绍了HtmlAgilityPack获取页面标题和H1标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿,我正在尝试通过以下操作从网页获取页面标题和H1标签
Hey all i am trying to get the page title and H1 tags from a webpage by doing the following
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都没有。我需要使用哪种类型的语法才能获得这两个标签?
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?
html代码如下所示:
The html code looks like this:
<!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.SelectSingleNode( // head / title)
和 doc.DocumentNode.SelectNodes( // body // h1)
。
或 doc.DocumentNode.Descendants( title)。SingleOrDefault()
和 doc.DocumentNode.Descendants( h1)
。
这篇关于HtmlAgilityPack获取页面标题和H1标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!