Sto lavorando con htmlAgilityPack e sto prendendo una tabella da un sito web.
Come posso modificare questo per restituire i valori per ogni riga, solo per ogni seconda colonna.
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("");
}
}
Puoi utilizzare il filtro di posizione XPath per ottenere solo il secondo <td>
figlio da ciascun <tr>
:
//table[@id='animal']//tbody//tr/td[2]
In realtà è uguale al selettore CSS :nth-of-type()
e mostra lo stesso risultato di :nth-child()
solo se tutti i bambini sono dello stesso tipo (significa che tutti i bambini sono <td>
in questo caso).