Tôi đang cố gắng sử dụng gói Nhanh nhẹn HTML để loại bỏ một số dữ liệu từ một trang web. Tôi thực sự đấu tranh trong việc tìm ra cách sử dụng các selectnodes bên trong một foreach và sau đó xuất dữ liệu vào một danh sách hoặc một mảng.Gói Agility HTML Chọn các nút
Đây là mã tôi đang làm việc cho đến thời điểm này.
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.
}
Tôi có nhận xét trong đoạn mã ở trên cho thấy những gì hiệu quả và những gì không và loại thứ tôi muốn hoàn thành.
Nếu có ai có bất kỳ đề xuất hoặc lần đọc nào tuyệt vời! Tôi đã tìm kiếm các diễn đàn và ví dụ và không đi qua bất cứ điều gì mà tôi có thể sử dụng.