2011-11-13 3 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이나 독서가 있다면 좋을 것입니다! 나는 포럼과 예제를 찾고 있었고 내가 사용할 수있는 모든 것을 건너 가지 않았다.

답변

11

'id'가 요소 이름이 아니기 때문에 주석으로 처리 된 첫 번째 문제는 SelectNodes이 아닙니다. 속성 이름입니다. 속성을 선택하고 값을 비교하기 위해 다른 표현식에서 올바른 구문을 사용했습니다. 예 : //ElementName[@attributeName='value']. 나는 심지어 [attributeName='value']가 작동한다고 생각하지만, 나는 이것을 테스트하지 않았다.

SelectNodes 함수의 구문을 "XPath"라고합니다. This link가 도움이됩니다.

노드를 선택하는 seller 노드는 alt 속성이있는 img 인 현재 반복에 대한 형제 노드입니다 (node). 그러나 당신이 원하는 정확한 구문은 단지 img[@alt]이라고 생각합니다.

다음 문제는 컴파일되지 않는다고 말하면서 오류 메시지를 확인하십시오. 아마도 인자 유형을 다시 불평 할 것입니다. sellers.Add 나는 다른 HtmlNode라는 이름을 찾고 있다고 생각한다.이 속성은 add 내부의 표현식이 반환하는 속성이 아니다.

또한 Html Agility 팩 문서 및 구문에 관한 기타 질문을 확인하십시오.