【问题标题】:C# web scraper navigate to aspx linkC# web scraper 导航到 aspx 链接
【发布时间】:2015-11-09 15:39:48
【问题描述】:

我正在构建一个 C# Windows Phone 8.1 应用程序。应用程序的一部分需要去查找特定网页上的信息。我需要的字段之一是可以在页面上的某些项目上找到的 URL,但是我发现 URL 是相对样式的格式

FullArticle.aspx?a=323495

我想知道在 C# 中是否有一种方法可以使用 HtmlAgilityPack、HttpWebRequest 等来找到指向实际页面的链接。代码 sn-p 如下。

private static TileUpdate processSingleNewsItem(HtmlNode newsItemNode)
{
    Debug.WriteLine("");
    var articleImage = getArticleImage(getNode(newsItemNode, "div", "nw-container-panel-articleimage"));
    var articleDate = getArticleDate(getNode(newsItemNode, "div", "nw-container-panel-articledate"));
    var articleSummary = getArticleSummary(getNode(newsItemNode, "div", "nw-container-panel-textarea"));
    var articleUrl = getArticleUrl(getNode(newsItemNode, "div", "nw-container-panel-articleimage"));
    return new TileUpdate{
        Date = articleDate,
        Headline = articleSummary,
        ImagePath = articleImage,
        Url = articleUrl
    };
}

private static string getArticleUrl(HtmlNode parentNode)
{
    var imageNode = parentNode.Descendants("a").FirstOrDefault();
    Debug.WriteLine(imageNode.GetAttributeValue("href", null));
    return imageNode.GetAttributeValue("href", null);
}

private static HtmlNode getNode(HtmlNode parentNode, string nodeType, string className)
{
    var children = parentNode.Elements(nodeType).Where(o => o.Attributes["class"].Value == className);
    return children.First();
}

将不胜感激任何想法或解决方案。干杯!

【问题讨论】:

  • 如果链接是相对格式的,难道不可以直接加上当前的URL作为前缀来获取完整的URL吗?也许将Reqest.AbsoluteUri 传入processSingleNewsItem

标签: c# html web-scraping


【解决方案1】:

在我的web crawler 中,这是我所做的:

foreach (HtmlNode link in doc.DocumentNode.SelectNodes(@"//a[@href]"))
{
    HtmlAttribute att = link.Attributes["href"];
    if (att == null) continue;
    string href = att.Value;
    if (href.StartsWith("javascript", StringComparison.InvariantCultureIgnoreCase)) continue;      // ignore javascript on buttons using a tags

    Uri urlNext = new Uri(href, UriKind.RelativeOrAbsolute);

    // Make it absolute if it's relative
    if (!urlNext.IsAbsoluteUri)
    {
        urlNext = new Uri(urlRoot, urlNext);
    }
    ...
}

【讨论】:

  • 谢谢,这解决了我的问题。我没想过要愚蠢地查看字符串是否包含在 Url 中的任何位置,所以您的回答提示我检查它并找到了字符串(以及我在您的示例中设置为 urlRoot 的 Url 的其余部分)。跨度>
猜你喜欢
  • 1970-01-01
  • 2018-08-15
  • 2021-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多