尝试从元素中获取文本:
<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>
我猜网站使用Reactjs,即使使用Poltergeist驱动程序,capybara也无法获取内容。有没有解决方法?
这是我的代码:
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')
答案 0 :(得分:0)
如果您已经与Capybara一起访问,则无需使用Nokogiri解析html。
def get_page_data(url)
visit(url)
p find(:css, '.points-text').text
end
将使用class points-text
打印元素中的可见文本答案 1 :(得分:0)
此代码适用于 selenium 和 webkit ,但它不适用于 poltergeist 驱动程序。 从截图中我可以看到网站上的javascript甚至都没有执行。
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')