用Ruby脚本抓取百度MP3新歌Top 100

软件和网站开发以及相关技术探讨
回复
头像
sevk
帖子: 2060
注册时间: 2007-05-08 16:26
系统: arch
来自: 火星内核某分子内某原子核内
联系:

用Ruby脚本抓取百度MP3新歌Top 100

#1

帖子 sevk » 2009-03-04 22:07

代码: 全选

require 'rubygems'
require 'hpricot'
require 'open-uri'
require 'iconv'

def _mktab(x)
  t0 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  p = t0.partition(x)
  p[1] + p[2] + p[0]
end

def decode(s)
  s.tr(_mktab(s[0].chr), s=~ /....:\// ? _mktab('h') : _mktab('f')) #http|ftp
end

def tiny_url(url, encode = false)
  result = open(encode ? URI.encode("http://tinyurl.com/api-create.php?url=#{url}") : "http://tinyurl.com/api-create.php?url=#{url}").read
  result =~ /^Error/ ? url : result
end

def actual_download_url(search_url, limit = 2)
  doc = Hpricot(open(search_url))
  doc.search("table#Tbs td.d a").map{|a| a.attributes["href"]}[0..limit].map {|url|
    decode(open(URI.encode(url)).read[/var I="([^"]*)"/, 1])
  }
end

def get_maidu_mp3_top100
  url = "http://list.mp3.baidu.com/list/newhits.html"
  doc = Hpricot(Iconv.conv("UTF8", "GBK", open(url).read))
  result = {}
  doc.search("table.list td:not(.th)").each{|t|
    name = t.inner_text.gsub(/\s+/, " ")
    search_url = t.search("a")[0].attributes["href"]
    result[name] = search_url
  }
  return result
end

def get_new_data
  local_data = File.open('data.yaml') { |file| YAML::load(file) } rescue {}
  remote_data = get_maidu_mp3_top100
  new_data = {}
  remote_data.each_pair { |key, value|
    unless local_data.has_key?(key)
      local_data[key] = value
      new_data[key] = value
    end
  }
  File.open('data.yaml', 'w') { |file| YAML.dump(local_data, file) }
  return new_data
end
 
原文: http://www.javaeye.com/topic/336765
笔记本 :
F208S : gentoo
A460P i3G D6 : UBUNTU + WIN7
UN43D1 : UBUNTU + WIN7
1000人超级QQ群 LINUX + WIN : 31465544 或 18210387
头像
eexpress
帖子: 58428
注册时间: 2005-08-14 21:55
来自: 长沙

Re: 用Ruby脚本抓取百度MP3新歌Top 100

#2

帖子 eexpress » 2009-03-05 11:02

幸好ruby基础了perl的精华。
● 鸣学
头像
ibear
帖子: 787
注册时间: 2006-10-19 8:43
来自: 长江口

Re: 用Ruby脚本抓取百度MP3新歌Top 100

#3

帖子 ibear » 2009-03-05 11:16

这个脚本能用?

我记得最近百度把下载页面地址放在js中生成了,貌似一个简单的加密,无法直接抓到了(在python中复制了该js,是可以解出正确的地址的,不过觉得百度太恶,干脆懒得上百度找歌了)
头像
lerosua
论坛版主
帖子: 8455
注册时间: 2007-11-29 9:41
联系:

Re: 用Ruby脚本抓取百度MP3新歌Top 100

#4

帖子 lerosua » 2009-03-05 12:04

ruby 不会用
回复