简体   繁体   中英

How to get dynamic page content with capybara

Trying to get text from elements:

<div class="points-text" data-reactid=".2765swfgy68.1.2.2.1:$sony-xperia-z1-compact.2.0.4.0.0.1">29,367 points</div>

I guess websites uses Reactjs and capybara can't get content even with Poltergeist driver. Is there any workaround?

Here is my code:

require 'rubygems'
require 'capybara'
require 'capybara/poltergeist'


Capybara.default_driver = :poltergeist
Capybara.register_driver :poltergeist do |app|
  Capybara::Poltergeist::Driver.new(app, {js_errors: false})
end


class WebScraper
  include Capybara::DSL

  def get_page_data(url)
    visit(url)
    doc = Nokogiri::HTML(page.html)
    p doc.css('.points-text')
  end
end


scraper = WebScraper.new
puts scraper.get_page_data('http://versus.com/en/sony-xperia-z1-compact')

There is no need to parse the html with Nokogiri if you're already visiting with Capybara.

def get_page_data(url)
  visit(url)
  p find(:css, '.points-text').text      
end

will print the visible text in the element with class points-text

This code works with selenium and webkit but it does NOT work with poltergeist driver. From the screenshots i can see that javascript on the website is not even executed.

require 'capybara'
require 'capybara-webkit'
require 'capybara/poltergeist'

Capybara.default_driver = :poltergeist
# Capybara.default_driver = :selenium
# Capybara.default_driver = :webkit
Capybara.register_driver :poltergeist do |app|
  Capybara::Poltergeist::Driver.new(app, {js_errors: false})
end
Capybara::Webkit.configure do |config|
  config.allow_unknown_urls
end


class WebScraper
  include Capybara::DSL

  def get_page_data(url)
    visit(url)

    max_same_times = 3
    same_times = 0
    old_points = nil
    20.times do |i|
      doc = Nokogiri::HTML(page.html)
      # p doc.css('.points-text')
      points = doc.css('.points-text')
      # p [same_times, max_same_times]
      if same_times == max_same_times
        break
      end
      if points.length > 0
        points = points[0].text
        # p [old_points, points]
        if old_points == points
          same_times += 1
        else
          same_times = 0
        end
        old_points = points
      end
      page.save_screenshot("#{i}.png")
    end
    old_points
  end
end


scraper = WebScraper.new
puts scraper.get_page_data('http://versus.com/en/sony-xperia-z1-compact')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM