【问题标题】:Get the titles and URLs of Yahoo result page in c#在c#中获取Yahoo结果页面的标题和URL
【发布时间】:2016-06-26 16:27:30
【问题描述】:

我想用 htmlagility 包获取 Yahoo 结果页面的标题和 URL

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;

            }
        }

它可以工作,但搜索结果中的所有链接都不是适当的链接如何省略广告链接、雅虎链接等。
我想访问正确的链接

【问题讨论】:

  • 你看过 HTML 源代码吗?区分搜索结果链接和广告链接非常容易。
  • @Rick 他们在<a class=" ac-algo ac-21th lh-15" 你能指导我访问他们吗?

标签: c# html css asp.net html-agility-pack


【解决方案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 语句,如 using ScrapySharp.Extensions; ,你就可以开始了。 (我使用它是因为它更容易引用 css 选择器而不是 xpath 表达式......)

关于跳过广告,我注意到这些雅虎搜索结果中的广告只会出现在最后一条记录中?假设我是正确的,请跳过最后一个。

这是我运行上述代码得到的输出:

【讨论】:

  • 它非常有效。但不幸的是它没有按雅虎结果页面的顺序返回结果。
猜你喜欢
  • 2014-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
  • 2020-05-07
  • 2022-11-02
相关资源
最近更新 更多