2011-07-14 9 views
0

これは私が持っているコードです。私はURLからすべてのimg srcを取得する方法を学ぼうとしています。しかし、imgs私の下のコードの変数は常にnullです。私は間違って何をしていますか?c#HtmlAgility Pack - 画像を取得できません。src

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 
using System.Net; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 
      doc.LoadHtml("http://archive.ncsa.illinois.edu/primer.html"); 
      HtmlAgilityPack.HtmlNodeCollection imgs = doc.DocumentNode.SelectNodes("//img"); 
      if (imgs != null) 
      { 
       foreach (HtmlAgilityPack.HtmlNode img in imgs) 
       { 
        string imgSrc = img.Attributes["src"].Value; 
       } 
      } 
      Console.ReadKey(); 
     } 
    } 
} 
+0

本当にnullですか?あなたはsrc属性で何もしません。それを印刷してみてください: 'Console.WriteLine(imgSrc);' – alexn

+0

はい、私はなぜそれがnullであると確信しているのですか?私がデバッグすると、 "if(imgs!= null)"の内部にさえ入っていないからです。 「if(imgs!= null)」という行をスキップしてConsole.ReadKey()に移動します。すぐに! –

答えて

3

あなたはHtmlDocument.LoadHtmlを使用しています.HTMLソースであり、URLではないように設計されています。

WebClientを使用してhtmlなどを取得できます。

WebClient wc = new WebClient(); 
string html = wc.DownloadString("http://archive.ncsa.illinois.edu/primer.html"); 
doc.LoadHtml(html); 

HtmlDocumentは、さまざまなソースからコンテンツを読み込むことができるようにするLoadもサポートしています。

+0

+1、あなたは私を打ち負かしました:-) –

+0

問題を解決してくれてありがとう:) –

関連する問題