【问题标题】:How to extract the html tag attribute?如何提取html标签属性?
【发布时间】:2011-10-02 06:50:36
【问题描述】:

我正在尝试开发我的第一个 RSS 新闻聚合器。我可以轻松地从 RSSItem 对象中提取链接、标题、发布日期。但是,我很难从提要项中提取图像。不幸的是,由于我的声誉低,所以我无法上传图片,所以不要帮我提取 <img> 的 src 属性的值,你能告诉我如何获取 @987654322 的 href attr 的值吗@ 标签。高度评价!!

这是字符串

<div style="text-align: center;"
    <a href="http://www.engadget.com/2011/07/10/element5s-mini-l-solarbag-brings-eco-friendly-energy-protectio/"></a>
</div>

编辑:

也许整个标题是错误的。有没有办法使用 XPath 找到值?

【问题讨论】:

  • 你的字符串在哪里?我想它应该在“这是字符串”部分之后
  • 这在我看来不像 RSS。你从哪里弄来的?
  • 约翰,这只是一个随机的 html。我没有足够的声誉在 SO 上嵌入图像和链接 :)

标签: c# html rss substring


【解决方案1】:

使用本文中回答的 HTMLAgilityPack:

How can I get values from Html Tags?

更多信息:

HTML 可能格式不正确,因此我们需要另一个更容错的解析器(除了 .net 中提供的 XML 解析器)。这就是 HTMLAgilityPack 的用武之地。

开始:

  1. 创建一个新的控制台应用程序

  2. 右键单击引用/管理 nuget 包(如果没有,请安装 NuGet)。

  3. 添加 html 敏捷性

一个工作示例:

        using System;
        using System.IO;
        using System.Text;
        using HtmlAgilityPack;

        namespace ConsoleApplication4
        {
            class Program
            {
                private const string html = 
        @"<?xml version=""1.0"" encoding=""ISO-8859-1""?>
        <div class='linkProduct' id='link' anattribute='abc'/>
         <bookstore>
         <book>
           <title lang=""eng"">Harry Potter</title>
           <price>29.99</price>
         </book>
         <book>
           <title lang=""eng"">Learning XML</title>
           <price>39.95</price>
         </book>
         </bookstore>
        ";

                static void Main(string[] args)
                {
                    HtmlDocument doc = new HtmlDocument();
                    byte[] byteArray = Encoding.ASCII.GetBytes(html); MemoryStream stream = new MemoryStream(byteArray);
                    var ts = new MemoryStream(byteArray);
                    doc.Load(ts);
                    var root = doc.DocumentNode;
                    var tag = root.SelectSingleNode("/div");
                    var attrib = tag.Attributes["anattribute"];
                    Console.WriteLine(attrib.Value);
                }
            }
        }

更进一步:

精通 XPath。这是一个很好的起点。

http://www.w3schools.com/xpath/xpath_syntax.asp

【讨论】:

  • 我使用了 HtmlAgilityPack,现在我可以提取图像了。感谢您的提示好先生!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 2015-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多