2011-11-13 48 views
6

我正在嘗試使用HTML敏捷性包從網站上刮取一些數據。我真的很努力研究如何在foreach中使用selectnodes,然後將數據導出到列表或數組。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. 

     } 

我在上面的代碼中有評論,顯示什麼有效,什麼沒有,以及我想要完成什麼。

如果有人有任何建議或閱讀,那就太棒了!我一直在尋找論壇和例子,並沒有涉及任何我可以使用的東西。

回答

11

您的第一個問題與註釋掉SelectNodes不起作用,因爲'id'不是一個元素名稱,它是一個屬性名稱。您在其他表達式中使用了正確的語法來選擇屬性並比較值。例如,//ElementName[@attributeName='value']。我認爲即使[attributeName='value']應該工作,但我沒有測試過。

SelectNodes函數內的語法被稱爲「XPath」。 This link可能會幫助你。

您正在選擇的seller節點是當前迭代的一個node的兄弟,它是具有alt屬性的img。不過,我認爲你想要的正確語法只是img[@alt]

下一個你說它不會編譯的問題,檢查錯誤信息,它可能會抱怨回參數類型。 sellers.Add我想要命名另一個HtmlNode,而不是添加內部表達式返回的屬性。

此外,請查看Html Agility pack文檔和其他有關語法的問題。