forked from foca/scraper
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscraper.rb
280 lines (230 loc) · 6.59 KB
/
scraper.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
## A minimalistic, declarative HTML scraper
class Scraper
attr_reader :doc
# Accepts string, open file, or Nokogiri-like document
def initialize(doc)
@doc = self.class.convert_document(doc)
initialize_plural_accessors
end
# Initialize a new scraper and process data
def self.parse(html)
new(html).parse
end
# Specify a new singular scraping rule
def self.element(*args, &block)
selector, name, delegate = parse_rule_declaration(*args, &block)
rules[name] = [selector, delegate]
attr_accessor name
name
end
# Specify a new plural scraping rule
def self.elements(*args, &block)
name = element(*args, &block)
rules[name] << true
end
# Let it do its thing!
def parse
self.class.rules.each do |target, (selector, delegate, plural)|
if plural
@doc.search(selector).each do |node|
send(target) << parse_result(node, delegate)
end
elsif node = @doc.at(selector)
send("#{target}=", parse_result(node, delegate))
end
end
self
end
protected
# `delegate` is optional, but should respond to `call` or `parse`
def parse_result(node, delegate)
if delegate
delegate.respond_to?(:call) ? delegate.call(node) : delegate.parse(node)
elsif node.respond_to? :inner_text
node.inner_text
else
node.to_s
end
end
# Rule declaration is in Hash or single argument form:
#
# { '//some/selector' => :name, :with => MyClass }
# #=> ['//some/selector', :name, MyClass]
#
# :title
# #=> ['title', :title, nil]
def self.parse_rule_declaration(*args, &block)
options, name = Hash === args.last ? args.pop : {}, args.first
delegate = options.delete(:with)
selector, property = name ? [name.to_s, name.to_sym] : options.to_a.flatten
raise ArgumentError, "invalid rule declaration: #{args.inspect}" unless property
# eval block in context of a new scraper subclass
delegate = Class.new(delegate || Scraper, &block) if block_given?
return selector, property, delegate
end
def self.rules
@rules ||= {}
end
def self.inherited(subclass)
subclass.rules.update self.rules
end
def initialize_plural_accessors
self.class.rules.each do |name, (s, k, plural)|
send("#{name}=", []) if plural
end
end
def self.convert_document(doc)
unless doc.respond_to?(:at) && doc.respond_to?(:search)
require 'nokogiri' unless defined? ::Nokogiri
Nokogiri::HTML(doc)
else
doc
end
end
end
## specs
if __FILE__ == $0
require 'spec/autorun'
HTML = DATA.read
class Article < Scraper
element 'h1' => :title
element 'a/@href' => :link
end
class TimestampedArticle < Article
element 'p.pubdate' => :published, :with => lambda { |node|
node.inner_text.sub('Published on ', '')
}
def published_date
@date ||= Date.parse published
end
end
class SpecialArticle < Article
element 'span'
end
class BlogScraper < Scraper
element :title
elements '#nav li' => :navigation_items
end
class OverrideBlogScraper < BlogScraper
elements :title
element '#nav li' => :navigation_items
end
class BlogWithArticles < BlogScraper
elements 'div.hentry' => :articles, :with => Article
end
class BlogWithTimestampedArticles < BlogScraper
elements 'div.hentry' => :articles, :with => TimestampedArticle
end
class BlogWithArticlesBlock < BlogScraper
elements 'div.hentry' => :articles do
element 'h1' => :title
end
end
class FakeHtmlParser
def initialize(name)
@name = name
end
def at(selector)
"fake #{@name}"
end
def search(selector)
(1..3).map { |n| self.class.new(@name + n.to_s) }
end
end
describe BlogWithTimestampedArticles do
before(:all) do
@blog = described_class.parse(HTML)
end
it "should have title" do
@blog.title.should == 'Maximum awesome'
end
it "should have articles" do
@blog.should have(2).articles
end
it "should have navigation items" do
@blog.should have(3).navigation_items
@blog.navigation_items.should == %w[Home About Help]
end
it "should have title, pubdate for first article" do
article = @blog.articles[0]
article.title.should == 'First article'
article.published.should == 'Oct 1'
article.published_date.month.should == 10
article.published_date.day.should == 1
article.link.should be_nil
end
it "should have title, link for second article" do
article = @blog.articles[1]
article.title.should == 'Second article'
article.published.should == 'Sep 5'
article.link.should == 'http://mislav.uniqpath.com'
end
end
describe SpecialArticle do
before(:all) do
doc = Nokogiri::HTML(HTML).at('//div[2]')
@article = described_class.parse(doc)
@parent_article = described_class.superclass.parse(doc)
end
it "should inherit title parsing from parent" do
@article.title.should == 'Second article'
end
it "should have additional 'span' rule" do
@article.span.should == 'My blog'
end
it "should not let superclass inherit rules" do
@parent_article.should_not respond_to(:span)
end
end
describe BlogWithArticles, 'with fake HTML parser' do
before(:all) do
doc = FakeHtmlParser.new('test')
@blog = described_class.parse(doc)
end
it "should have fake title" do
@blog.title.should == 'fake test'
end
it "should have fake articles" do
titles = @blog.articles.map { |a| a.title }
titles.should == ['fake test1', 'fake test2', 'fake test3']
end
end
describe OverrideBlogScraper do
before(:all) do
@blog = described_class.parse(HTML)
end
it "should have plural titles" do
@blog.title.should == ['Maximum awesome']
end
it "should have singular navigation item" do
@blog.navigation_items.should == 'Home'
end
end
describe BlogWithArticlesBlock do
before(:all) do
@blog = described_class.parse(HTML)
end
it "should have article objects" do
titles = @blog.articles.map { |article| article.title }
titles.should == ['First article', 'Second article']
end
end
end
__END__
<title>Maximum awesome</title>
<body>
<ol id="nav">
<li>Home</li>
<li>About</li>
<li>Help</li>
</ol>
<div class="hentry">
<h1>First article</h1>
<p class="pubdate">Published on Oct 1</p>
</div>
<div class="hentry">
<h1>Second article</h1>
<p class="pubdate">Published on Sep 5</p>
<span><a href="http://mislav.uniqpath.com">My blog</a></span>
</div>
</body>