HTML敏捷包选择节点

8
我是一个有用的助手,可以为您翻译文本。

我正在尝试使用HTML Agility包从一个网站上抓取一些数据。 我真的很难弄清楚如何在foreach中使用selectnodes,然后将数据导出到列表或数组中。

这是我目前使用的代码。

       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.

        }

我在上面的代码中有注释,显示了什么有效,什么无效以及我想要实现的东西。
如果有人有任何建议或阅读资料,那就太好了!我一直在搜索论坛和示例,但没有找到我可以使用的东西。
1个回答

11
你在注释掉的SelectNodes中遇到了问题,因为'id'不是一个元素名称,而是属性名称。你已经在其他选择属性和比较其值的表达式中使用了正确的语法。例如,//ElementName[@attributeName='value']。我认为甚至[attributeName='value']也应该可以工作,但我没有测试过。 SelectNodes函数内部的语法称为"XPath"。这个链接可能会帮助你。
你选择的seller节点是当前迭代的node的一个具有alt属性的img标签的兄弟节点。然而,我认为你想要的正确语法只是img[@alt]
接下来的问题是你说它无法编译,检查错误消息,它可能会抱怨参数类型。我认为sellers.Add正在寻找命名另一个HtmlNode,而不是一个属性,这就是add内部表达式返回的内容。
此外,请查看Html Agility包文档和其他有关语法的问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接