Pro*_*kzy 16 html javascript c# visual-studio web-scraping
我有一个webBrowser,以及Visual Studio中的标签,基本上我要做的是从另一个网页抓取一个部分.
我尝试使用WebClient.DownloadString和WebClient.DownloadFile,在javascript加载内容之前,他们都给了我网页的源代码.我的下一个想法是使用WebBrowser工具,只是在页面加载后调用webBrowser.DocumentText并且不起作用,它仍然提供了页面的原始来源.
有没有办法可以抓住javascriptload后的页面?
这是我试图抓的页面.
http://www.regulations.gov/#!documentDetail;D=APHIS-2013-0013-0083
我需要从该页面获取评论,该页面是生成的.
wbe*_*ett 40
问题是浏览器通常执行javascript,结果是更新的DOM.除非您可以分析javascript或拦截它使用的数据,否则您将需要像浏览器那样执行代码.在过去我遇到了同样的问题,我利用selenium和PhantomJS来渲染页面.在呈现页面之后,我将使用WebDriver客户端来导航DOM并检索我需要的内容,发布在AJAX之后.
在高层次上,这些是以下步骤:
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");
Run Code Online (Sandbox Code Playgroud)
有关selenium,phantomjs和webdriver的更多信息,请访问以下链接:
http://docs.seleniumhq.org/projects/webdriver/
编辑:更简单的方法
它似乎有一个NuGet包的phantomjs,这样你不需要集线器(我用了一个集群做这样大规模的报废):
安装Web驱动程序:
Install-Package Selenium.WebDriver
Run Code Online (Sandbox Code Playgroud)
安装嵌入式exe:
Install-Package phantomjs.exe
Run Code Online (Sandbox Code Playgroud)
更新的代码:
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");
Run Code Online (Sandbox Code Playgroud)
小智 5
感谢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/{YOUR_API_KEY}/",
pageRequestJson).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
Run Code Online (Sandbox Code Playgroud)
是的。
| 归档时间: |
|
| 查看次数: |
19393 次 |
| 最近记录: |