【问题标题】:Extract both text and image using htmlagilitypack使用 htmlagilitypack 提取文本和图像
【发布时间】:2012-07-19 12:27:20
【问题描述】:

我正在从网页中提取内容。在网页中,电话号码和电子邮件 ID 等信息存储在图像中。我想提取图像以及该表中的文本。在输出字符串中,我希望输出与带有图像和文本的网页中显示的方式相同。

以下是网页内容。

<table>
<tr>
   <td>text</td>
   <td><img src="" /></td>
</tr>
<tr>
   <td>text</td>
   <td><img src="" /></td>
</tr>
<tr>
   <td>text</td>
   <td><img src="" /></td>
</tr>
</table>

我可以像这样提取文本和图像吗:

文字图片

文字图片

文字图片

【问题讨论】:

    标签: c# html c#-4.0 html-parsing


    【解决方案1】:
    HtmlDocument doc = new HtmlDocument();
    doc.Load("file.htm");
    HtmlNode imgNode = doc.DocumentElement.selectSingleNode("/table/tr/td/img");
    
    //Just get Images only
    foreach (HtmlNode img in doc.DocumentElement.SelectNodes("//img"))
    {
      string imgSrc = img.Attributes["src"].Value;
    }
    
    //get td's and ignore img in it
    foreach (HtmlNode td in doc.DocumentElement.SelectNodes("//td"))
    {
      HtmlNode img = td.ChildNodes["img"];
      if(img == null)
      {
        string tdText = td.InnerText;
      }
    }
    
    //Get Images that have style attribute
    foreach (HtmlNode img in doc.DocumentElement.SelectNodes("//img[@style]"))
    {
      string style = img.Attributes["style"].Value.ToLower();
      style = style.Replace("background:url('", "");
      style = style.Replace("')", "");
     //now you have the image url from the background
    
    }
    

    【讨论】:

    • 谢谢你,HatSoft。 DocumentElement 在我的代码中支持。我尝试使用 DocumentNode。我还有一个问题,如何提取 img 标签的背景图像并存储在我的系统中。
    • @user1516690 我可以给你xpath来提取包含背景的样式属性:等,但如果你他们没有图像文件扩展名
    • HatSoft,这就是我面临的问题。我怎样才能得到这个网址中的图像。这可以从url获取图像吗?这是我从网页中提取 html 内容时得到的。
    • @user1516690 我可以为您获取网址,此网址返回图像内容,因此您必须以这种方式使用该网址
    【解决方案2】:

    试试这个

    foreach (HtmlNode img in root.SelectNodes("//img"))
    {
        string att = img.Attributes["src"].Value;
        anchorTags.Add(att);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-28
      • 2013-10-21
      • 2011-02-16
      • 2014-10-16
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多