【问题标题】:Scraping webpage generated by JavaScript with C#用 C# 抓取 JavaScript 生成的网页
【发布时间】:2014-08-08 22:28:30
【问题描述】:

我有一个网络浏览器,在Visual Studio 中有一个标签,基本上我想做的是从另一个网页中抓取一个部分。

我尝试使用WebClient.DownloadStringWebClient.DownloadFile,它们都在JavaScript 加载内容之前给了我网页的源代码。我的下一个想法是使用网络浏览器工具并在页面加载后调用webBrowser.DocumentText,但这不起作用,它仍然给了我页面的原始来源。

有没有办法可以抓取页面帖子JavaScript 加载?

【问题讨论】:

    标签: c# javascript html visual-studio web-scraping


    【解决方案1】:

    感谢wbennet,我发现了PhantomJSCloud.com。足够的免费服务可以通过网络API 调用来报废页面。

    public static string GetPagePhantomJs(string url)
    {
        using (var client = new System.Net.Http.HttpClient())
        {
            client.DefaultRequestHeaders.ExpectContinue = false;
            var pageRequestJson = new System.Net.Http.StringContent
                (@"{'url':'" + url + "','renderType':'html','outputAsJson':false }");
            var response = client.PostAsync
                ("https://PhantomJsCloud.com/api/browser/v2/{YOUT_API_KEY}/",
                pageRequestJson).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }
    

    是的。

    【讨论】:

    • 服务很好,但速度很慢
    【解决方案2】:

    好的,我将向您展示如何使用 phantomjs 和使用 c# 的 selenuim 启用 javascript

    1. 创建一个新的控制台项目,随意命名
    2. 在你的右手边打开解决方案浏览器
    3. 右键单击引用单击管理 NuGet 包
    4. 一个窗口会显示点击浏览而不是安装 Selenium.WebDriver
    5. 从这里下载 phantomjs Phantomjs
    6. 在你的主函数中输入这段代码

          var options = new PhantomJSOptions();
          options.AddAdditionalCapability("IsJavaScriptEnabled", true);
          IWebDriver driver = new PhantomJSDriver("phantomjs Folder Path", options);
          driver.Navigate().GoToUrl("https://www.yourwebsite.com/");
      
          try
          {
              string pagesource = driver.PageSource;
              driver.FindElement(By.Id("yourelement"));
              Console.Write("yourelement founded");
      
          }
          catch (Exception e)
          {
              Console.WriteLine(e.Message);
      
          }
      
          Console.Read();
      

    不要忘记将您的网站和您要查找的元素以及您机器中的 phantomjs.exe 路径放在下面的代码中

    祝您编码愉快,感谢wbennett

    【讨论】:

      【解决方案3】:

      问题是浏览器通常会执行 javascript,结果是更新了 DOM。除非您可以分析 javascript 或拦截它使用的数据,否则您将需要像浏览器一样执行代码。过去我遇到过同样的问题,我使用 selenium 和 PhantomJS 来呈现页面。在它呈现页面之后,我将使用 WebDriver 客户端来导航 DOM 并检索我需要的内容,发布 AJAX。

      概括地说,这些是步骤:

      1. 已安装硒:http://docs.seleniumhq.org/
      2. 将 selenium 集线器作为服务启动
      3. 下载的phantomjs(无头浏览器,可以执行javascript):http://phantomjs.org/
      4. 以指向 selenium 集线器的 webdriver 模式启动 phantomjs
      5. 在我的抓取应用程序中安装了 webdriver 客户端 nuget 包:Install-Package Selenium.WebDriver

      以下是 phantomjs webdriver 的示例用法:

      var options = new PhantomJSOptions();
      options.AddAdditionalCapability("IsJavaScriptEnabled",true);
      
      var driver = new RemoteWebDriver( new URI(Configuration.SeleniumServerHub),
                          options.ToCapabilities(),
                          TimeSpan.FromSeconds(3)
                        );
      driver.Url = "http://www.regulations.gov/#!documentDetail;D=APHIS-2013-0013-0083";
      driver.Navigate();
      //the driver can now provide you with what you need (it will execute the script)
      //get the source of the page
      var source = driver.PageSource;
      //fully navigate the dom
      var pathElement = driver.FindElementById("some-id");
      

      有关 selenium、phantomjs 和 webdriver 的更多信息可以在以下链接中找到:

      http://docs.seleniumhq.org/

      http://docs.seleniumhq.org/projects/webdriver/

      http://phantomjs.org/

      编辑:更简单的方法

      似乎有一个用于 phantomjs 的 nuget 包,因此您不需要集线器(我使用集群以这种方式进行大量报废):

      安装网络驱动:

      Install-Package Selenium.WebDriver
      

      安装嵌入式exe:

      Install-Package phantomjs.exe
      

      更新代码:

      var driver = new PhantomJSDriver();
      driver.Url = "http://www.regulations.gov/#!documentDetail;D=APHIS-2013-0013-0083";
      driver.Navigate();
      //the driver can now provide you with what you need (it will execute the script)
      //get the source of the page
      var source = driver.PageSource;
      //fully navigate the dom
      var pathElement = driver.FindElementById("some-id");
      

      【讨论】:

      • 感谢完美的例子。完美运行。
      • 我试过了,但是 driver.Url 没有改变。也不例外。只是通过,它仍然是动作:空白。所以导航返回像 。我尝试了另一个网址。稍等片刻,然后转到下一行。代码结尾当然找不到一些ID。有什么想法吗?
      猜你喜欢
      • 1970-01-01
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      相关资源
      最近更新 更多