Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 使用Nokogiri的CSS选择_Ruby_Nokogiri - Fatal编程技术网

Ruby 使用Nokogiri的CSS选择

Ruby 使用Nokogiri的CSS选择,ruby,nokogiri,Ruby,Nokogiri,我正在尝试使用Nokogiri进行HTML抓取,但没有得到预期的结果 在这个特定的URL上,我正在查看特定位置的交易,并希望在该页面上显示交易详细信息.small deals cont是页面的CSS选择器,类似地,.deal title是交易标题的CSS选择器 require 'rubygems' require 'nokogiri' require 'open-uri' url = "http://www.snapdeal.com/local-deals-Chennai-all?categ

我正在尝试使用Nokogiri进行HTML抓取,但没有得到预期的结果

在这个特定的URL上,我正在查看特定位置的交易,并希望在该页面上显示交易详细信息
.small deals cont
是页面的CSS选择器,类似地,
.deal title
是交易标题的CSS选择器

require 'rubygems' 
require 'nokogiri'
require 'open-uri'

url = "http://www.snapdeal.com/local-deals-Chennai-all?category=all&HID=dealHeader_all"

doc =Nokogiri::HTML(open(url))

puts doc.at_css("title").text

doc.css(".small-deals-cont").each do |item|
  puts item.at_css(".deal-title")
end

为了防止刮擦,他们可能在初始页面加载之后加载内容(使用javascript)。在这种情况下,Nokogiri帮不了你,你需要一个更完善的系统——也许可以使用


然而,最后,你不应该刮。这个网站的所有者已经制定了预防方法,你应该尊重这一点。检查API。

Nokogiri实际上适用于此,我们不需要为此使用mechanize。下面是代码:

require 'rubygems'
require 'nokogiri'
require 'open-uri'
require 'csv'

hotel= Array.new

cuisine=Array.new

url= "http://www.abcd.com"

1.upto(5) do |page_num|
  doc = Nokogiri::HTML(open("http://www.abcd.com/cit/restaurants?page=#{page_num}"))
  puts doc.at_css("title").text

  doc.css("article").each do |item|
    hotel << item.at_css("a").text
    cuisine << item.at_css(".tags").text
  end
end

@hotel=hotel
@cuisine=cuisine

(0..@hotel.length - 1).each do|index|

  puts "Hotel: #{@hotel[index]}"
  puts "Cuisine: #{@cuisine[index]}"
  puts " "

end


CSV.open("output2.csv", "wb") do |row|

  row << ["Hotel", "Cuisine"]

  (0..@hotel.length - 1).each do |index|
    row << [@hotel[index], @cuisine[index]]
  end

end
需要“rubygems”
需要“nokogiri”
需要“打开uri”
需要“csv”
新酒店
烹饪=阵列。新
url=”http://www.abcd.com"
1.最多(5)个do |页码|
doc=Nokogiri::HTML(打开http://www.abcd.com/cit/restaurants?page=#{page_num}”))
将文档置于css(“标题”)文本中
css文件(“文章”)。每个do |项目|

酒店+1推荐使用API。Mechanize对JavaScript没有帮助,因为它不是JavaScript解释器。如果需要刮削,Watir或其附属公司会更好。