2011-11-13 13 views
6

HTMLアジリティパックを使用してサイトからデータをスクラップしようとしています。私は実際にforeach内でselectノードを使用してデータをリストまたは配列にエクスポートする方法を考え出すのに苦労しています。HTMLアジリティパックノードを選択

ここまでは私がこれまで取り組んでいるコードです。

 string result = string.Empty; 

     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(http://www.amazon.com/gp/offer-listing/B002UYSHMM/); 
     request.Method = "GET"; 

     using (var stream = request.GetResponse().GetResponseStream()) 
     using (var reader = new StreamReader(stream, Encoding.UTF8)) 
     { 
      result = reader.ReadToEnd(); 
     } 

     HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 
     doc.Load(new StringReader(result)); 
     HtmlNode root = doc.DocumentNode; 

     string itemdesc = doc.DocumentNode.SelectSingleNode("//h1[@class='producttitle']").InnerText; //this works perfectly to get the title of the item 
     //HtmlNodeCollection sellers = doc.DocumentNode.SelectNodes("//id['bucketnew']/div/table/tbody/tr/td/ul/a/img/@alt");//this does not work at all in getting the alt attribute from the seller images 
     HtmlNodeCollection prices = doc.DocumentNode.SelectNodes("//span[@class='price']"); //this works fine getting the prices 
     HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='resultsset']/table/tbody[@class='result']/tr"); //this is the code I am working on to try to collect each tr in the result. I then want to eather add each span.price to a list from this and also add each alt attribute from the seller image to a list. Once I get this working I will want to use an if statement in the case that there is text for the seller name instead of an image. 

     List<string> sellers = new List<string>(); 
     List<string> prices = new List<string>(); 

     foreach (HtmlNode node in nodes) 
     { 
      HtmlNode seller = node.SelectSingleNode(".//img/@alt"); // I am not sure if this works 
      sellers.Add(seller.SelectSingleNode("img").Attributes["alt"]); //this definitly does not work and will not compile. 

     } 

上記のコードには、動作しているものとできていないものと何ができているのかを示すコメントがあります。

誰もが素晴らしいだろう任意のsugguestionsや読書を持っている場合!私はフォーラムや例を探していて、私が使うことのできるものは何も出てこなかった。 「idは」要素の名前ではありませんので、コメントアウトSelectNodes

答えて

11

あなたの最初の問題は動作しません、それは属性名です。他の式で正しい構文を使用して、属性を選択し値を比較しています。例えば、//ElementName[@attributeName='value']。私は[attributeName='value']でも動作するはずだと思うが、私はこれをテストしていない。

SelectNodes関数内の構文は、「XPathの」と呼ばれています。 This linkがあなたを助けてくれるかもしれません。

ノードを選択しているsellerは、現在の反復ではalt属性のimgであるnodeの兄弟です。しかし、私はあなたが望む正しい構文がちょうどimg[@alt]だと思う。

あなたはそれがコンパイルされませんと言う次の問題は、エラーメッセージを確認し、それはおそらく、引数の型をバック文句されます。 sellers.Add私は、別のHtmlNodeという名前をつけようとしていると思います。それは、add内の式が返す属性ではありません。

また、Htmlの敏捷性パックのドキュメントや構文に関する他の質問をチェックしてください。