用c#抓取JavaScript生成的网页

Scraping webpage generated by JavaScript with C#

本文关键字:网页 JavaScript 抓取      更新时间:2023-09-26

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

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

是否有办法抓取JavaScript加载的页面帖子?

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

在高层次上,有以下步骤:

  1. 安装selenium: http://docs.seleniumhq.org/
  2. 将selenium hub作为服务启动
  3. 下载的phantomjs(一个可以执行javascript的无头浏览器):http://phantomjs.org/
  4. 在webdriver模式下启动phantomjs,指向selenium hub
  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/

EDIT: easy Method

似乎有一个用于phantomjs的nuget包,这样您就不需要集线器了(我使用集群以这种方式进行大量清除):

安装web驱动程序:

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");

多亏了wbennet,我发现了PhantomJSCloud.com。有足够的免费服务通过web 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/{YOUR_API_KEY}/",
            pageRequestJson).Result;
        return response.Content.ReadAsStringAsync().Result;
    }
}

是的。

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

  1. 创建一个新的控制台项目,将其命名为您想要的名称
  2. 转到右侧的解决方案资源管理器
  3. 右键点击参考,点击管理NuGet包
  4. 一个窗口将显示点击浏览然后安装Selenium。WebDriver
  5. 下载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