Baiduserp

此gem的目的是专门用来解析百度的搜索结果页.最主要的功能是能得到十个自然结果的排名和URL,以及左侧/右侧的广告的排名/URL.

目前这个只是一个基本能用的版本,可能会有各种各样的问题,欢迎提BUG.

Installation

1 系统要求

Linux或Mac. Linux最好使用新版本的Ubuntu或Fedora系列.

2 安装ruby环境

只支持ruby1.9及以上. 最好的安装ruby的方法是通过RVM,RVM的使用方法可以搜索一下,有很多教程.

在最新的Ubuntu或Fedora系列的Linux中,也可以通过apt-get或yum安装ruby1.9.

3 安装gem依赖

需要依赖nokogiri这个gem.而这个gem需要系统中的两个库. 所以在ubuntu或者fedora下需要

$ sudo apt-get install libxslt-dev libxslt libxml2-dev libxml2  # ubuntu
$ sudo yum install libxml2-devel libxml2 libxslt libxslt-devel  # fedora

以上依赖安装完成后,

$ gem install nokogiri

4 最后我们安装 baiduserp gem

$ gem install baiduserp

Usage

ruby 代码示例

require 'baiduserp'
require 'open-uri'
require 'pp'

pp Baiduserp.search 'keyword'

pp Baiduserp.parse open(http://www.baidu.com/s?wd=keyword).read.encode('UTF-8')

另外为了方便非ruby程序使用以及一次性调试,也提供了命令行调用方法,可以通过JSON格式交换数据:

$ baiduserp -h
Usage: 
1. baiduserp -s 'keyword' # search 'keyword' and print parse result
2. baiduserp -s 'keyword' -o output.json # -o means save result to a file
3. baiduserp -f 'file path' # parse html source code from file
4. baiduserp -s 'keyword' -j # search 'keyword' and print parse result in JSON format
    -s, --search Keyword             Search Keyword & Parse SERP
    -j, --jsonprint                  Print result in JSON format
    -o, --output Output              Save Result to File in JSON format
    -f, --file File                  Parse Local File

最终结果采用了哈希表和数组相互嵌套的数据结构,其中,每条结果的paid值中,0代表自然结果,1代表左侧广告,2代表右侧广告.结果示例如下:

$ baiduserp -s 

Contributing

欢迎大家帮忙协助继续完善这个gem:

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

或者可以到Issue页面提交问题,可以提BUG,新的需求,各种建议,等等.