C# - HTML Agility Pack - 節點集合 - 循環表行,選擇nth-child(2)

c# html-agility-pack

我正在使用htmlAgilityPack,並從網站上抓取一張桌子。

如何修改此值以返回每行,每隔一列的值。

public static void SearchAnimal(string param)
        {
            string prm = param;
            string url = "http://xxx/xxx.action?name=";
            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url+prm);
            //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //StreamReader stream = new StreamReader(response.GetResponseStream());
            //string final_response = stream.ReadToEnd();
            var webGet = new HtmlWeb();
            var doc = webGet.Load(url + prm);

            HtmlNodeCollection tr = doc.DocumentNode.SelectNodes("//table[@id='animal']//tbody//tr//td");

                  for(int i = 0; i <= tr.Count; ++i){
                    var link = tr
                       .Descendants("a")
                       .First(x => x.Attributes["href"] != null);
                    string hrefValue = link.Attributes["href"].Value;
                    string name = link.InnerHtml;
                    Match match = Regex.Match(hrefValue, @"(\d+)$");
                    Console.ForegroundColor = ConsoleColor.DarkGray;
                    Console.WriteLine("Result " + tr + ":");
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.WriteLine("Animal Name: " + name);
                    Console.WriteLine("Animal Key: " + match.Value);
                    Console.WriteLine("-------------------------");
                    Console.WriteLine("");

                       }



        }

一般承認的答案

您可以使用XPath位置過濾器從每個<tr>僅獲取第二個<td>子項:

//table[@id='animal']//tbody//tr/td[2]

它實際上等於CSS :nth-of-type()選擇器,並且只有當所有子節點屬於同一類型時才顯示相同的輸出:nth-child() (在這種情況下,所有子<td>都是<td> )。



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow