2016-06-23 31 views
2

我想雅虎結果頁面的標題和URL與htmlagility包獲取雅虎結果頁面的標題和URL在c#

HtmlWeb w = new HtmlWeb(); 

string SearchResults = "https://en-maktoob.search.yahoo.com/search?p=" + query.querytxt; 

var hd = w.Load(SearchResults); 


    var nodes = hd.DocumentNode.SelectNodes("//a[@cite and @href]"); 
    if (nodes != null) 
    { 
     foreach (var node in nodes) 
     { 

      { 
       string Text = node.Attributes["title"].Value; 
       string Href = node.Attributes["href"].Value; 

      } 
     } 

它的工作原理,但在搜索結果中的所有鏈接都是不恰當的聯繫如何省略廣告鏈接,雅虎鏈接等。
我要訪問的正確鏈接

+0

你有沒有看HTML源代碼?區分搜索結果鏈接和廣告鏈接相當容易。 – Rick

+0

@他們在' mary

回答

1

這個怎麼樣:

HtmlWeb w = new HtmlWeb(); 

string search = "https://en-maktoob.search.yahoo.com/search?p=veverke"; 
//ac-algo ac-21th lh-15 
var hd = w.Load(search); 

var titles = hd.DocumentNode.CssSelect(".title a").Select(n => n.InnerText); 
var links = hd.DocumentNode.CssSelect(".fz-15px.fw-m.fc-12th.wr-bw.lh-15").Select(n => n.InnerText); 

for (int i = 0; i < titles.Count() - 1; i++) 
{ 
    var title = titles.ElementAt(i); 
    string link = string.Empty; 
    if (links.Count() > i) 
     link = links.ElementAt(i); 

    Console.WriteLine("Title: {0}, Link: {1}", title, link); 
} 

請記住,我使用的擴展方法CssSelect,從NuGet包的ScrapySharp。像安裝HtmlAgilityPack一樣安裝它,然後在代碼頂部添加一條使用語句,如using ScrapySharp.Extensions;,並且您很好。 (我使用它,因爲它更容易參考css選擇器而不是xpath表達式...)

關於跳過廣告,我注意到這些雅虎搜索結果中的廣告只會出現在最後一條記錄中?假設我是正確的,只需跳過最後一個。

這裏的輸出我得到的運行上面的代碼:

enter image description here

+0

它工作很多。但不幸的是它不會按照Yahoo結果頁的順序返回結果。 – mary