加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 使用Nokogiri的CSS选择

发布时间:2020-12-17 03:03:51 所属栏目:百科 来源:网络整理
导读:我正在尝试使用Nokogiri进行 HTML抓取,但是没有得到预期的结果. 在这个特定的URL上,我查看了特定位置的交易,并希望在该页面上显示交易详细信息. .small-deals-cont是页面的CSS选择器,类似的.deal-title是交易标题的CSS选择器. require 'rubygems' require 'n
我正在尝试使用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

解决方法

Nokogiri实际上是为此工作,我们不需要使用机械化.这是它的代码:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读