我对过多的刮擦技术有点新,所以我一直在测试一堆。我正在看的一个测试页面是here。我注意到,通过Capybara的刮板正在返回我期望的结果 - JS运行后的HTML。这里是代码:为什么webkit通过capybara获得与CasperJS不同的结果?
class Scraper
include Capybara::DSL
Capybara.run_server = false
Capybara.current_driver = :webkit
def test_scrape
visit "https://www.facebook.com/pages/Buddha-Bodai-Vegetarian-Restaurant/117609928256672?sk=info"
if body.match /pagelet_nearby_places_results/
has_xpath?("//div[@id='pagelet_nearby_places_results']")
end
body
end
end
这显然是一个非常基本的测试。例如,您可以通过查看页面上Foursquare链接的HTML来正确加载。
<a class="uiIconText" href="https://www.facebook.com/l.php?u=https%3A%2F%2Ffoursquare.com%2Fv%2Fbuddha-bodai%2F459b830af964a5208b401fe3%3Fref%3Datw&h=0AQH4z1yv&s=1"
...
我还测试实施CasperJS解决方案,如下图所示:
var casper = require('casper').create({
pageSettings: {
javascriptEnabled: true,
loadImages: false,
loadPlugins: false,
userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5'
}
});
result = {};
casper.start("https://www.facebook.com/pages/Buddha-Bodai-Vegetarian-Restaurant/117609928256672?sk=info", function() {
var body = this.getHTML();
if(body.indexOf('pagelet_nearby_places_results') >= 0){
casper.waitForSelector('div#pagelet_nearby_places_results', function() {
result.html = this.getHTML();
});
}else{
result.html = body;
}
});
casper.run(function complete() {
this.echo(JSON.stringify(result, null, 4));
this.exit();
});
为此,我得到这似乎是HTML的JS加载之前不同的结果。在这种情况下,Foursquare的链接被注释掉和代码标签内:
<code class="hidden_elem" id="u_0_i"><!-- <div class="_5ay5"><div data-gt="{"vertex_section":"VertexLinksSection"}"><div class="_gl"><div class="_117 _4qd"><h3>Links</h3></div><div class="_gm"><ul class="uiList _4kg _6-h _6-j _6-i"><li class="_6zy"><table class="uiGrid _51mz" cellspacing="0" cellpadding="0"><tbody><tr class="_51mx"><td class="_51m-"><a class="uiIconText" href="https://www.facebook.com/l.php?u=https%3A%2F%2Ffoursquare.com%2Fv%2Fbuddha-bodai%2F459b830af964a5208b401fe3%3Fref%3Datw&h=UAQG_81FD&s=1"
...
所不同的是陌生的,原因有二:1。 显然CasperJS(其中坐在PhantomJS)JS运行之前不能返回HTML。这就是PhantomJS的全部要点。 2.我的解决方案都基于webkit
请注意,我也试着让卡斯帕等5秒钟(应该足够的时间),以帮助排除waitForSelector行事有趣。鉴于这是一个非常简单的测试案例,我希望有人能够对结果为什么会有所不同。
谢谢!