【问题标题】:Scraping single page websites抓取单页网站
【发布时间】:2017-12-23 22:56:00
【问题描述】:

我想从 bet365.com 获取数据,但问题是当我下载 page-source 时,page-source 不包含该数据。正如我搜索的那样,在单页应用程序中,所有内容都不会立即加载。我尝试了以下代码,但无法获得所需的数据。谁能帮忙?

    public string GetGeneratedHTML(string url)
    {
        URL = url;
        Thread t = new Thread(new ThreadStart(WebBrowserThread));
        t.SetApartmentState(ApartmentState.STA);
        t.Start();
        t.Join();

        return GeneratedSource;
    }

    private void WebBrowserThread()
    {
        WebBrowser wb = new WebBrowser();
        wb.Navigate(URL);

        wb.DocumentCompleted +=
            new WebBrowserDocumentCompletedEventHandler(
                wb_DocumentCompleted);

        while (wb.ReadyState != WebBrowserReadyState.Complete)
            Application.DoEvents();

        //Added this line, because the final HTML takes a while to show up
        GeneratedSource = wb.Document.Body.InnerHtml;

        wb.Dispose();
    }`enter code here`

    private void wb_DocumentCompleted(object sender,
        WebBrowserDocumentCompletedEventArgs e)
    {
        WebBrowser wb = (WebBrowser)sender;
        GeneratedSource = wb.Document.Body.InnerHtml;
    }

【问题讨论】:

  • 好像 bet365 不喜欢刮板
  • 另外,在页面源代码中找不到我在网站上看到的代码

标签: c# web-scraping


【解决方案1】:

使用浏览器开发工具的“网络”选项卡查看它们调用哪些 REST 端点来获取数据。然后直接调用端点并获取数据,而不是抓取 html。

【讨论】:

  • 只是想说声谢谢.. 没想到这一点几乎感觉很愚蠢,但您的评论让我走上了正轨。试图证明在项目中实例化基于 selenium 的 docker 容器以将渲染的源作为服务获取是合理的,但我想我会先做一些研究。我试图抓住的 SPA 确实做了一个 REST 调用,我可以在网络选项卡中隔离它.. 哈哈,完美。谢谢大佬。
【解决方案2】:

您可以尝试设置延迟事件/计时器来检查页面是否有新数据/html 的可用性。然后使用你自己编写的函数,就像你基本上已经 wb_DocumentCompleted 一样。效率不高,但非常准确。祝你好运!..

protected System.Timers.Timer MonitorTimer = new System.Timers.Timer();
public void Initialize()
{
    MonitorTimer.Elapsed += new ElapsedEventHandler(UpdateEvent);
    MonitorTimer.Interval = 1000;
    MonitorTimer.Enabled = true;
}
protected object TimerLock = new object();
public void UpdateEvent(object source, ElapsedEventArgs e)
{
    lock (TimerLock)
    {
        doc = (mshtml.HTMLDocument)wbProfile.Document;
        // What you are looking for that only appears later. -->
        if(doc.body.innerHTML.toString().IndexOf("foo") != -1) 
        {
            // Do something useful..
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-18
    相关资源
    最近更新 更多