cnm*_*muc 6 javascript ajax web-crawler htmlunit angularjs
根据https://developers.google.com/webmasters/ajax-crawling/docs/html-snapshot,使用HtmlUnit(2.13)我尝试使用AngularJS(1.2.1)为网页创建快照.
我的Java代码是:
WebClient webClient = new WebClient();
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
webClient.setCssErrorHandler(new SilentCssErrorHandler());
webClient.getOptions().setCssEnabled(true);
webClient.getOptions().setRedirectEnabled(false);
webClient.getOptions().setAppletEnabled(false);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setPopupBlockerEnabled(true);
webClient.getOptions().setTimeout(10000);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(true);
webClient.getOptions().setThrowExceptionOnScriptError(true);
webClient.getOptions().setPrintContentOnFailingStatusCode(true);
HtmlPage page = webClient.getPage(new WebRequest(new URL("..."), HttpMethod.GET));
webClient.waitForBackgroundJavaScript(5000);
String result = page.asXml();
Run Code Online (Sandbox Code Playgroud)
虽然webClient.getPage(...)不会抛出任何异常,但结果字符串仍然包含"未评估的角度表达式",例如
<div>
{{name}}
</div>
Run Code Online (Sandbox Code Playgroud)
我知道http://htmlunit.10904.n7.nabble.com/htmlunit-to-scrape-angularjs-td29931.html#a30075,但那里给出的推荐也不起作用.
当然,相同的GET请求在所有当前浏览器中都没有例外.
有任何想法/经验如何让HtmlUnit与AngularJS一起使用?
更新:
我创建了一个HTMLUnit 错误报告.
目前,我将我的实现切换到了PhantomJS.也许这段代码片段可以帮助其他人解决类似的问题:
System.setProperty("phantomjs.binary.path", "phantomjs.exe");
DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true);
caps.setCapability("takesScreenshot", false);
PhantomJSDriver driver = new PhantomJSDriver(caps);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(new URL("..."));
String result = driver.getPageSource();
Run Code Online (Sandbox Code Playgroud)
Update2: 我现在手动渲染我的页面,因为Google抓取工具现在呈现Angular网站
小智 8
我有同样的问题,但无法使用显式引导,因为角度e2e测试不适用于显式引导程序.
我通过使用解决了这个问题
<html id="ng-app" class="ng-app: appmodule;">
Run Code Online (Sandbox Code Playgroud)
代替
<html ng-app="appmodule">
Run Code Online (Sandbox Code Playgroud)
htmlunit测试工作和e2e测试也工作.
很可能,htmlunit没有(完全?)支持document.querySelectorAll().angularInit()使用此方法来查找ng-app指令.
ng-app指令的语法变体适用于angularInit()中的document.querySelectorAll()调用.
当我的单页应用程序使用 angularjs 1.0.4 时,我的类似代码可以正常工作;我要做的唯一不同的事情是告诉 htmlunit 使用 FIREFOX_17 而不是 htmlunit 2.12 中的默认 IE8 (类似于您提供的链接,但使用 FIREFOX_17 而不是 FIREFOX_10)
final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_17);
Run Code Online (Sandbox Code Playgroud)
我升级到 angularjs 1.2,我的页面显示了所有角度占位符。