【问题标题】:Why does webkit through capybara get different results than CasperJS?为什么 webkit 通过 capybara 得到的结果与 CasperJS 不同?
【发布时间】:2014-02-07 20:11:51
【问题描述】:

我对大量可用的抓取技术有点陌生,所以我一直在测试一堆。我正在查看的一个测试页面是here。我注意到我通过 Capybara 运行的刮板正在返回我期望的结果 - JS 运行后的 HTML。代码如下:

  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&amp;h=0AQH4z1yv&amp;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();
});

为此,在加载 JS 之前,我得到了不同的结果,看起来像是 HTML。本例中的四方链接被注释掉并位于代码标记内:

<code class="hidden_elem" id="u_0_i"><!-- <div class="_5ay5"><div data-gt="{&quot;vertex_section&quot;:&quot;VertexLinksSection&quot;}"><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&amp;h=UAQG_81FD&amp;s=1"
...

这种差异很奇怪,原因有两个: 1. 显然 CasperJS(位于 PhantomJS 上)无法在 JS 运行之前返回 HTML。这就是 PhantomJS 的全部意义所在。 2.我的两个方案都是基于webkit的

请注意,我还尝试让 Casper 等待 5 秒(应该足够的时间)以帮助排除 waitForSelector 的行为很有趣。鉴于这是一个非常简单的测试用例,我希望有人可以深入了解为什么结果不同。

谢谢!

【问题讨论】:

    标签: webkit web-scraping phantomjs casperjs


    【解决方案1】:

    我认为这是一个错误,所以我在这里记录了它: https://github.com/ariya/phantomjs/issues/11964

    【讨论】:

      猜你喜欢
      • 2021-05-05
      • 1970-01-01
      • 2019-09-07
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多