robostripper 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,18 @@
1
+ docs
2
+ *.gem
3
+ *.rbc
4
+ .bundle
5
+ .config
6
+ .yardoc
7
+ Gemfile.lock
8
+ InstalledFiles
9
+ _yardoc
10
+ coverage
11
+ doc/
12
+ lib/bundler/man
13
+ pkg
14
+ rdoc
15
+ spec/reports
16
+ test/tmp
17
+ test/version_tmp
18
+ tmp
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in robostripper.gemspec
4
+ gemspec
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2013 Brian Muller
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,111 @@
1
+ = Robostripper
2
+
3
+ Robostripper takes the magic of Nokogiri and makes it easy to treat a website like a database.
4
+
5
+ == Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'robostripper'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install robostripper
18
+
19
+ == Usage
20
+
21
+ Let's say you want to pull down information about a business from the Yellow Pages website.
22
+
23
+ === Single Item
24
+
25
+ For the first example, let's pretend you want a single business' information and you already have the URL.
26
+
27
+ First, create a class and then describe one of the items on the page that you want to pull out (in this case, the business details):
28
+
29
+ class YellowPage < Robostripper::Resource
30
+ end
31
+
32
+ YellowPage.add_item :details do
33
+ phone "p.phone strong"
34
+ street "span.street-address"
35
+ city "span.locality"
36
+ state "span.region"
37
+ zip "span.postal-code"
38
+ address { [ street, city, state, zip ].join(" ") }
39
+ payments { scan("dd.def-payment").split(", ").map(&:strip) }
40
+ end
41
+
42
+ In the add_item block, I've described the attributes that I want to pull out and the query necessary to pull that information out. For each attribute, you can give either CSS selector code or XPath or a mix of the two (as an array). Alternatively, you can provide a block that will be executed each time you ask for the attribute. For instance, in the example above, the *address* attribute references all of the other address attributes ad joins them together.
43
+
44
+ The arguments to attributes are used in a call to the method _scan_, which is used explicitly in the *payments* attribute. See the section below for more details about document scanning. The payments on the page I'll be pulling from are comma separated - but I want to produce an array - so I split by commas and strip the results.
45
+
46
+ It is then trivial to pull information from the page:
47
+
48
+ url = "http://www.yellowpages.com/silver-spring-md/mip/quarry-house-tavern-3342829"
49
+ yp = YellowPage.new(url)
50
+ yp.details.payments
51
+ => ["MASTER CARD", "DISCOVER", "AMEX", "VISA", "CASH ONLY"]
52
+ yp.details.phone
53
+ => "(301) 587-8350"
54
+ yp.details.address
55
+ => "8401 Georgia Ave, Silver Spring MD 20910"
56
+
57
+
58
+ === Pages with Lists
59
+
60
+ For the second example, let's say you want to be able to search the Yellow Pages website and then get the details for each matching business.
61
+
62
+ First, let's define our listing class.
63
+
64
+ class YellowPagesList < Robostripper::Resource
65
+ def initialize(city, name)
66
+ # First, replace spaces with dashes
67
+ city = city.gsub(',', '').gsub(' ', '-')
68
+ name = name.gsub(' ', '-')
69
+ super("http://www.yellowpages.com/#{city}/#{name}")
70
+ end
71
+ end
72
+
73
+ Because the Yellow Pages site performs searches based on URL structure, we've simply crafted the structure based on an input city and business name. Now, we can explain how to get each result out of the page:
74
+
75
+ YellowPagesList.add_list :businesses, "div.result" do
76
+ name "h3.business-name a"
77
+ url "h3.business-name a", :attribute => 'href'
78
+ details { YellowPage.new(url).details }
79
+ end
80
+
81
+ For this example, each business' information can be foudn within a _div.result_. Each of those will have three attributes. The first two are pulled out of the div in the same way as the single result described above. The details attribute, however, is special in that it creates a new *YellowPage* (which we defined above). When you ask for a business' details, then Robostripper will go get the URL and parse out the details.
82
+
83
+ Putting it all together:
84
+
85
+ ypl = YellowPagesList.new("Washington, DC", "Quarry House Tavern")
86
+ # the first match is all we care about
87
+ business = ypl.businesses.first
88
+ # now, get the details like we did above
89
+ business.details.phone
90
+ => "(301) 587-8350"
91
+ business.details.zip
92
+ => "20910"
93
+
94
+ We can now search the Yellow Pages website and get the details for any business. Like a Robot.
95
+
96
+ == Scanning Documents
97
+
98
+ If a block isn't given to an attribute definition in _add_list_ or _add_item_ then the arguments are passed along to the method _scan_. The method _scan_ takes two arguments:
99
+
100
+ 1. A CSS path selector, an XPath selector, or an array containing a any mix of the two. If the argument is an array, then each selection is applied in order. For instance:
101
+
102
+ [ "p.something", "a[first()]" ]
103
+
104
+ will first find paragraphs with a class of _something_ using a CSS selctor, and then will pull out the first _a_ element using the XPath selector.
105
+
106
+ 2. The second argument is an options hash. By default, _scan_ will just return the _text_ content of all matching nodes from #1. The following options can modify that:
107
+ * *:all* => true: This signifies that _scan_ should just return all matching elements, without sucking out the text.
108
+ * *:nontext* => ' ': If this option is specified, it will replace all non-text elements with a spacing string. This is necessary, for instance, if a website uses
109
+ <br /> elements to separate strings and you want to preserve the separation. For instance, if you want "123 Fake St<br />A City, CA" to have a space between the
110
+ street and the city.
111
+ * *:attribute* => 'href': Use this to pull out an element's specific attribute rather than it's inner text.
@@ -0,0 +1,9 @@
1
+ require "bundler/gem_tasks"
2
+ require 'rdoc/task'
3
+
4
+ RDoc::Task.new("doc") { |rdoc|
5
+ rdoc.title = "Robostripper - Strip HTML websites like a Robot"
6
+ rdoc.rdoc_dir = 'docs'
7
+ rdoc.rdoc_files.include('README.rdoc')
8
+ rdoc.rdoc_files.include('lib/**/*.rb')
9
+ }
@@ -0,0 +1,3 @@
1
+ require "robostripper/version"
2
+ require "robostripper/resource"
3
+ require "robostripper/http"
@@ -0,0 +1,21 @@
1
+ require 'httparty'
2
+ require 'nokogiri'
3
+
4
+ module Robostripper
5
+ module HTTP
6
+ HEADERS = {
7
+ 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
8
+ 'Accept-Charset' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
9
+ 'Accept-Language' => 'en-US,en;q=0.8',
10
+ 'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.101 Safari/537.11'
11
+ }
12
+
13
+ def self.get(url)
14
+ response = HTTParty.get(url, :headers => HEADERS)
15
+ if response.code != 200
16
+ raise "Got response code of #{response.code} for #{url}"
17
+ end
18
+ Nokogiri::HTML response.body
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,69 @@
1
+ require 'uri'
2
+ require 'set'
3
+
4
+ module Robostripper
5
+ class Resource
6
+ def initialize(source)
7
+ @html = (source.is_a? String) ? HTTP.get(source) : source
8
+ @cached = {}
9
+ @attrs = Set.new
10
+ end
11
+
12
+ def encode(text)
13
+ URI.encode(text)
14
+ end
15
+
16
+ def self.add_list(name, path, &block)
17
+ define_method(name) {
18
+ @cached[name] ||= @html.css(path).map { |result|
19
+ Resource.new(result).tap { |r| r.instance_eval &block }
20
+ }
21
+ }
22
+ end
23
+
24
+ def self.add_item(name, &block)
25
+ define_method(name) {
26
+ @cached[name] ||= Resource.new(@html).tap { |r| r.instance_eval &block }
27
+ }
28
+ end
29
+
30
+ def method_missing(method, *args, &block)
31
+ return super if method == :to_ary or (args.length == 0 and block.nil?)
32
+ @attrs << method
33
+
34
+ if block.nil? and args.length == 0
35
+ block = lambda { nil }
36
+ elsif block.nil?
37
+ options = (args.length == 1) ? {} : args[1]
38
+ block = lambda { scan(args.first, options) }
39
+ end
40
+
41
+ define_singleton_method(method, &block)
42
+ end
43
+
44
+ def scan(paths, options = {})
45
+ result = @html
46
+ paths = [ paths ] unless paths.is_a? Array
47
+ paths.each { |path|
48
+ result = result.search(path)
49
+ }
50
+
51
+ if result.nil? or result.length == 0
52
+ nil
53
+ elsif options.fetch(:all, false)
54
+ result
55
+ elsif options.has_key? :nontext
56
+ result.children.select(&:text?).map(&:text).join(options[:nontext])
57
+ elsif options.has_key? :attribute
58
+ result.first[options[:attribute]]
59
+ else
60
+ result.text
61
+ end
62
+ end
63
+
64
+ def to_s
65
+ attrs = @attrs.to_a.inject({}) { |h, attr| h[attr] = send(attr); h }
66
+ "<#{self.class.name} #{attrs}>"
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,3 @@
1
+ module Robostripper
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,22 @@
1
+ lib = File.expand_path('../lib', __FILE__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require 'robostripper/version'
4
+
5
+ Gem::Specification.new do |gem|
6
+ gem.name = "robostripper"
7
+ gem.version = Robostripper::VERSION
8
+ gem.authors = ["Brian Muller"]
9
+ gem.email = ["bamuller@gmail.com"]
10
+ gem.description = %q{Strip HTML websites as though they provided a REST interface. Like a Robot.}
11
+ gem.summary = %q{Strip HTML websites as though they provided a REST interface. Like a Robot.}
12
+ gem.homepage = "https://github.com/bmuller/robostripper"
13
+
14
+ gem.files = `git ls-files`.split($/)
15
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
16
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
17
+ gem.require_paths = ["lib"]
18
+ gem.add_dependency("httparty", ">= 0.9.0")
19
+ gem.add_dependency("nokogiri", ">= 1.5.6")
20
+ gem.add_development_dependency("rake")
21
+ gem.add_development_dependency("rdoc")
22
+ end
metadata ADDED
@@ -0,0 +1,113 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: robostripper
3
+ version: !ruby/object:Gem::Version
4
+ prerelease:
5
+ version: 0.0.1
6
+ platform: ruby
7
+ authors:
8
+ - Brian Muller
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+
13
+ date: 2012-12-29 00:00:00 Z
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: httparty
17
+ requirement: &id001 !ruby/object:Gem::Requirement
18
+ none: false
19
+ requirements:
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: 0.9.0
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: *id001
26
+ - !ruby/object:Gem::Dependency
27
+ name: nokogiri
28
+ requirement: &id002 !ruby/object:Gem::Requirement
29
+ none: false
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: 1.5.6
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: *id002
37
+ - !ruby/object:Gem::Dependency
38
+ name: rake
39
+ requirement: &id003 !ruby/object:Gem::Requirement
40
+ none: false
41
+ requirements:
42
+ - - ">="
43
+ - !ruby/object:Gem::Version
44
+ version: "0"
45
+ type: :development
46
+ prerelease: false
47
+ version_requirements: *id003
48
+ - !ruby/object:Gem::Dependency
49
+ name: rdoc
50
+ requirement: &id004 !ruby/object:Gem::Requirement
51
+ none: false
52
+ requirements:
53
+ - - ">="
54
+ - !ruby/object:Gem::Version
55
+ version: "0"
56
+ type: :development
57
+ prerelease: false
58
+ version_requirements: *id004
59
+ description: Strip HTML websites as though they provided a REST interface. Like a Robot.
60
+ email:
61
+ - bamuller@gmail.com
62
+ executables: []
63
+
64
+ extensions: []
65
+
66
+ extra_rdoc_files: []
67
+
68
+ files:
69
+ - .gitignore
70
+ - Gemfile
71
+ - LICENSE.txt
72
+ - README.rdoc
73
+ - Rakefile
74
+ - lib/robostripper.rb
75
+ - lib/robostripper/http.rb
76
+ - lib/robostripper/resource.rb
77
+ - lib/robostripper/version.rb
78
+ - robostripper.gemspec
79
+ homepage: https://github.com/bmuller/robostripper
80
+ licenses: []
81
+
82
+ post_install_message:
83
+ rdoc_options: []
84
+
85
+ require_paths:
86
+ - lib
87
+ required_ruby_version: !ruby/object:Gem::Requirement
88
+ none: false
89
+ requirements:
90
+ - - ">="
91
+ - !ruby/object:Gem::Version
92
+ hash: 4100496691358447740
93
+ segments:
94
+ - 0
95
+ version: "0"
96
+ required_rubygems_version: !ruby/object:Gem::Requirement
97
+ none: false
98
+ requirements:
99
+ - - ">="
100
+ - !ruby/object:Gem::Version
101
+ hash: 4100496691358447740
102
+ segments:
103
+ - 0
104
+ version: "0"
105
+ requirements: []
106
+
107
+ rubyforge_project:
108
+ rubygems_version: 1.8.24
109
+ signing_key:
110
+ specification_version: 3
111
+ summary: Strip HTML websites as though they provided a REST interface. Like a Robot.
112
+ test_files: []
113
+