2017-04-20 1 views
0

Je suis actuellement en train d'explorer certains sites Web et d'en récupérer des informations pour les stocker dans une base de données en vue d'une utilisation ultérieure. J'utilise HtmlAgilityPack et j'ai réussi à le faire pour quelques sites maintenant mais pour une raison quelconque, celui-ci me cause des problèmes. Je suis assez nouveau pour la syntaxe XPath, donc je suis probablement en train de faire des bêtises.Récupération de XPath <a> href, text, et <span>

Heres ce que le code du site ressemble que je suis en train de retreive:

<form ... id="_subcat_ids_"> 
    <input ....> 
    <ul ...> 
    <li ....> 
     <input .....> 
     <a class="facet-seleection multiselect-facets " 
     .... href="INeedThisHref#1"> 
     Text I Need       //need to retrieve this text between then <a></a> 
     <span class="subtle-note">(2)</span> //I Need that number from inside the span 
     </a> 
    </li> 
    <li ....> 
     <input .....> 
     <a class="facet-seleection multiselect-facets " 
     .... href="INeedThisHref#2"> 
     Text I Need #2      //need to retrieve this text between then <a></a> 
     <span class="subtle-note">(6)</span> //I Need that number from inside the span 
     </a> 
    </li> 

Chacun de ceux qui représente un élément sur une page, mais je suis seulement intéressé par ce qui se passe avec chaque <a></a>. Je veux récupérer cette valeur href à l'intérieur du <a>, puis le texte entre l'ouverture et la fermeture, puis j'ai besoin du texte à l'intérieur du <span>. J'ai laissé de côté les choses à l'intérieur des autres balises car elles ne permettent pas d'identifier chaque élément, la classe à l'intérieur <a> est la seule chose qu'ils partagent, et ils sont tous à l'intérieur du form avec id="_subcat_ids_".

Heres mon code:

try 
{ 
    string fullUrl = "..."; 
    HtmlWeb web = new HtmlWeb(); 
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; 
    HtmlDocument html = web.Load(fullUrl); 

    foreach (HtmlNode node in html.DocumentNode.SelectNodes("//form[@id='_subcat_ids_']")) //this gets me into the form 
    { 
    foreach (HtmlNode node2 in node.SelectNodes(".//a[@class='facet-selection multiselect-facets ']")) //this should get me into the the <a> tags, but it is throwing a fit with 'object reference not set to an instance of an object' 
    { 
     //get the href 
     string tempHref = node2.GetAttributeValue("href", string.Empty); 
     //get the text between <a> 
     string tempCat = node2.InnerText.Trim(); 
     //get the text between <span> 
     string tempNum = node2.SelectSingleNode(".//span[@class='subtle-note']").InnerText.Trim(); 
    } 
    } 
} 
catch (Exception ex) 
{ 
    Console.Write("\nError: " + ex.ToString()); 
} 

Cette première boucle foreach ne pas l'erreur, mais le second me donne object reference not set to an instance of an object à la ligne où ma seconde boucle foreach est. Comme je l'ai déjà mentionné, je suis encore novice dans cette syntaxe, j'ai utilisé ce type de méthode sur un autre site avec beaucoup de succès mais j'ai des problèmes avec ce site. Des conseils seraient appréciés.

+0

Vérifiez l'exactitude des détails fournis car il y a plusieurs fautes de frappe/inexactitudes dans votre expression '' XPath' et html' exemple comme 'seleection' /' selection', espaces nombre dans le nom de la classe ... – Andersson

Répondre

0

Eh bien j'ai tout compris, voici le code

foreach (HtmlNode node in html.DocumentNode.SelectNodes("//form[@id='_subcat_ids_']")) 
{ 
    //get the categories, store in list 
    foreach (HtmlNode node2 in node.SelectNodes("..//a[@class='facet-selection multiselect-facets ']//text()[normalize-space() and not(ancestor::span)]")) 
    { 
    string tempCat = node2.InnerText.Trim(); 
    categoryList.Add(tempCat); 
    Console.Write("\nCategory: " + tempCat);   
    } 
    foreach (HtmlNode node3 in node.SelectNodes("..//a[@class='facet-selection multiselect-facets ']")) 
    { 
    //get href for each category, store in list 
    string tempHref = node3.GetAttributeValue("href", string.Empty); 
    LinkCatList.Add(tempHref); 
    Console.Write("\nhref: " + tempHref); 
    //get the number of items from categories, store in list 
    string tempNum = node3.SelectSingleNode(".//span[@class='subtle-note']").InnerText.Trim(); 
    string tp = tempNum.Replace("(", ""); 
    tempNum = tp; 
    tp = tempNum.Replace(")", ""); 
    tempNum = tp; 
    Console.Write("\nNumber of items: " + tempNum + "\n\n"); 
    } 
} 

fonctionne comme un charme