【问题标题】:Scrape Dynamic Data from Website Using C# HTMLAGILITYPACK使用 C# HTMLAGILITYPACK 从网站抓取动态数据
【发布时间】:2019-01-18 01:32:45
【问题描述】:

我正在使用 HTMLAGILITY Pack 抓取数据,但页面无法正确加载。

我需要我的代码等待页面完全加载。

有一些解决方法可以在表单中使用浏览器,但我不需要在表单中使用它。

这是我需要废弃的Link,下面是我的代码。

HtmlWeb web = new HtmlWeb();
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        HtmlAgilityPack.HtmlDocument doc = web.Load(website);
         var goldTypes = doc.DocumentNode.SelectNodes("//h2[@class='gold-box-title']").ToList();
       var goldPrices = doc.DocumentNode.SelectNodes("//span[@class='gold-box-price--sale'").ToList();

          for (int i = 0; i < 2; i++)
             {
               string  goldPrice = goldPrices[i].InnerText;
               string  goldType = goldTypes[i].InnerText;

             }

【问题讨论】:

  • 您的代码看起来不错。你遇到了什么问题?
  • @TheSoftwareJedi 我得到的是变量名而不是它们的值
  • 网站包含angular数据

标签: c# web-scraping html-agility-pack


【解决方案1】:

你是对的,所有数据都在“buyable-gold”元素的“:buyable”属性中以结构化 json 格式提供。

我做了一个快速测试,这应该是你想要的。这将为您提供包含所需数据的结构化对象列表。

HtmlWeb web = new HtmlWeb();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HtmlAgilityPack.HtmlDocument doc = web.Load("https://www.ezrsgold.com/buy-runescape-gold");

var buyGoldNodes = doc.DocumentNode.SelectNodes("//buyable-gold");

var buyableJsonList = buyGoldNodes.Select(x => HttpUtility.HtmlDecode(x.Attributes[":buyable"].Value)).ToList();

var buyables = buyableJsons.Select(x => JsonConvert.DeserializeObject<Buyable>(x)).ToList();

那么您的 Buyable 类将如下所示。

public class Buyable
{
    public int id { get; set; }
    public string sku { get; set; }
    public int game_id { get; set; }
    public string title { get; set; }
    public int min_qty { get; set; }
    public int max_qty { get; set; }
    public string base_price { get; set; }
    public string sale_price { get; set; }
    public Bulk_Price[] bulk_price { get; set; }
    public string delivery_time { get; set; }
    public string description { get; set; }
    public object sort_order { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public string price { get; set; }
    public bool on_sale { get; set; }
    public int discount_from { get; set; }
}

public class Bulk_Price
{
    public string qty { get; set; }
    public string price { get; set; }
}

【讨论】:

  • 谢谢这个工作,但我不知道它是怎么做到的?可买黄金节点在哪里?我找不到它。
  • 查看源码可以找到。只是检查它不会显示它。
  • 那我怎么才能找到呢?
  • 只需查看页面源代码(右键单击 -> 在 chrome 中查看页面源代码),然后像搜索任何内容一样搜索标签。
  • 是的——记住检查器在 JS 改变了这么多之后向你展示了 DOM。 HtmlAgility 使用原始 HTML 源代码 - 这通常是不同的。
猜你喜欢
  • 2020-11-24
  • 1970-01-01
  • 2022-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
  • 1970-01-01
  • 2012-07-20
相关资源
最近更新 更多