2013-07-12 10 views
5

cerco di praticare "HtmlAgilityPack", ma sto avendo alcuni problemi riguardanti questo. ecco quello che ho codificato, ma non riesco a ottenere correttamente il titolo e la descrizione di una pagina web ... Se qualcuno mi può illuminare su un mio errore :)HtmlAgilityPack ottenere Titolo e meta

... 
public static void Main(string[] args) 
    { 
     string link = null; 
     string str; 
     string answer; 

     int curloc; // holds current location in response 
     string url = "http://stackoverflow.com/"; 

     try 
     { 

      do 
      { 
       HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(url); 
       HttpWReq.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5"; 
       HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse(); 
       //url = null; // disallow further use of this URI 
       Stream istrm = HttpWResp.GetResponseStream(); 
       // Wrap the input stream in a StreamReader. 
       StreamReader rdr = new StreamReader(istrm); 

       // Read in the entire page. 
       str = rdr.ReadToEnd(); 

       curloc = 0; 
       //WebPage result; 
       do 
       { 
        // Find the next URI to link to. 
        link = FindLink(str, ref curloc); //return the good link 
        Console.WriteLine("Title found: " + curloc); 
        //title = Title(str, ref curloc); 

        if (link != null) 
        { 
         Console.WriteLine("Link found: " + link); 
         using (System.Net.WebClient client = new System.Net.WebClient()) 
         { 
          HtmlDocument htmlDoc = new HtmlDocument(); 
          var html = client.DownloadString(url); 
          htmlDoc.LoadHtml(link); //chargement de HTMLAgilityPack 
          var htmlElement = htmlDoc.DocumentNode.Element("html"); 

          HtmlNode node = htmlDoc.DocumentNode.SelectSingleNode("//meta[@name='description']"); 
          if (node != null) 
          { 
           string desc = node.GetAttributeValue("content", ""); 
           Console.Write("DESCRIPTION: " + desc); 
          } 
          else 
          { 
           Console.WriteLine("No description"); 
          } 

          var titleElement = 
               htmlDoc.DocumentNode 
                .Element("html") 
                .Element("head") 
                .Element("title"); 
          if (titleElement != null) 
          { 
           string title = titleElement.InnerText; 
           Console.WriteLine("Titre: {0}", title); 
          } 
          else 
          { 
           Console.WriteLine("no Title"); 
          } 
          Console.Write("Done"); 
         } 
         Console.Write("Link, More, Quit?"); 
         answer = Console.ReadLine(); 
        } 
        else 
        { 
         Console.WriteLine("No link found."); 
         break; 
        } 
       } while (link.Length > 0); 

       // Close the Response. 
       HttpWResp.Close(); 
      } while (url != null); 
     } 
catch{ ...} 

Grazie in anticipo :)

+0

C'è un meta tag su stackoverflow? Il mio browser non mostra nel codice sorgente della pagina –

+0

A proposito del titolo: basta provare htmlDoc.DocumentNode.SelectSingleNode ("// titolo") –

+0

sì, non ci sono meta tag su StackOverflow ... e con "HtmlNode nodo = HTMLDOC .DocumentNode.SelectSingleNode ("// titolo");" il risultato è vuoto ... –

risposta

17

Go in questo modo:

HtmlNode mdnode = htmlDoc.DocumentNode.SelectSingleNode("//meta[@name='description']"); 

       if (mdnode != null) 
       { 
       HtmlAttribute desc; 

       desc = mdnode.Attributes["content"]; 
       string fulldescription = desc.Value; 
       Console.Write("DESCRIPTION: " + fulldescription); 
       } 
+0

grazie mille :) –

+2

non dovrebbe essere "se (mdnode! = Null)" sulla linea 3? – XzaR

+0

@XzaR sì, sembra così – prospector

1

credo che il problema è qui:

htmlDoc.LoadHtml(link); //chargement de HTMLAgilityPack 

dovrebbe essere:

htmlDoc.LoadHtml(html); //chargement de HTMLAgilityPack 

loadHTML si aspetta una stringa con il codice sorgente HTML, non l'url.

E probabilmente si desidera modificare:

var html = client.DownloadString(url); 

a

var html = client.DownloadString(link); 
1

Hai usato un punto di interruzione e la linea di andata per la linea per vedere dove l'errore potrebbe essere che si verificano?

Se avete, quindi provare qualcosa di simile:

string result = string.Empty; 
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com"); 
     request.Method = "GET"; 
     try 
     { 
      using (var stream = request.GetResponse().GetResponseStream()) 

      using (var reader = new StreamReader(stream, Encoding.UTF8)) 
      { 
       result = reader.ReadToEnd(); 
      } 
     } 
     HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument(); 
     htmlDoc.LoadHtml(result); 

Poi riporto il resto del codice sotto il htmlDoc.LoadHtml

+0

sì, ma ho lo stesso problema quando provo ad ottenere il "Website_title". –

+0

string desc = website_title.InnerText; – prospector

+0

grazie, funziona bene per il titolo, ma non ho ottenuto risultati per la descrizione. Provo questo: stringa desc = description.GetAttributeValue ("content =", ""); –

0
public string HtmlAgi(string url, string key) 
    { 
     //string.Format 
     var Webget = new HtmlWeb(); 
     var doc = Webget.Load(url); 
     HtmlNode ourNode = doc.DocumentNode.SelectSingleNode(string.Format("//meta[@name='{0}']", key)); 
     if (ourNode != null) 
     { 
      return ourNode.GetAttributeValue("content", ""); 
     } 
     else 
     { 
      return "not fount"; 
     } 

    } 
1
[HttpPost] 
    public ActionResult Create(WebSite website) 
    { 



     string desc = HtmlAgi(website.Url, "description"); 
     string keyword = HtmlAgi(website.Url, "Keywords"); 

     if (ModelState.IsValid) 
     { 

      var userId = ((CustomPrincipal)User).UserId; 
      r.Create(new WebSite 
      { 
       Description = desc, 
       Tags = keyword, 
       Url = website.Url, 
       UserId = userId, 
       Category = website.Category 

      }); 

      return RedirectToAction("Index"); 
     } 

     return View(website); 
    }