titi 0.0.2 → 0.0.3
Sign up to get free protection for your applications and to get access to all the features.
- data/LICENSE.textile +96 -0
- data/README.textile +37 -23
- data/VERSION +1 -1
- data/lib/titi.rb +0 -2
- data/lib/titi/ignore/hpricot.rb +31 -0
- data/lib/titi/ignore/html_parser.rb +387 -0
- data/lib/titi/ignore/matcher.rb +254 -0
- data/lib/titi/{parse_tree.rb → ignore/parse_tree.rb} +2 -2
- data/lib/titi/provider/twitter/models.rb +0 -1
- data/titi.gemspec +7 -5
- metadata +8 -6
- data/LICENSE +0 -20
- data/lib/titi/matcher.rb +0 -157
data/LICENSE.textile
ADDED
@@ -0,0 +1,96 @@
|
|
1
|
+
The titi code is __Copyright (c) 2010 Infochimps, Inc__
|
2
|
+
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at "http://www.apache.org/licenses/LICENSE-2.0":http://www.apache.org/licenses/LICENSE-2.0
|
4
|
+
|
5
|
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an **AS IS** BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
|
6
|
+
|
7
|
+
h1. Apache License
|
8
|
+
|
9
|
+
Apache License
|
10
|
+
Version 2.0, January 2004
|
11
|
+
http://www.apache.org/licenses/
|
12
|
+
|
13
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
14
|
+
|
15
|
+
<notextile><div class="toggle"></notextile>
|
16
|
+
|
17
|
+
h2. 1. Definitions.
|
18
|
+
|
19
|
+
* **License** shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
20
|
+
* **Licensor** shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
21
|
+
* **Legal Entity** shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, **control** means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
* **You** (or **Your**) shall mean an individual or Legal Entity exercising permissions granted by this License.
|
23
|
+
* **Source** form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
24
|
+
* **Object** form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
25
|
+
* **Work** shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
26
|
+
* **Derivative Works** shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
27
|
+
* **Contribution** shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, **submitted** means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
28
|
+
* **Contributor** shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
29
|
+
|
30
|
+
<notextile></div><div class="toggle"></notextile>
|
31
|
+
|
32
|
+
h2. 2. Grant of Copyright License.
|
33
|
+
|
34
|
+
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
35
|
+
|
36
|
+
|
37
|
+
<notextile></div><div class="toggle"></notextile>
|
38
|
+
|
39
|
+
h2. 3. Grant of Patent License.
|
40
|
+
|
41
|
+
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
42
|
+
|
43
|
+
<notextile></div><div class="toggle"></notextile>
|
44
|
+
|
45
|
+
h2. 4. Redistribution.
|
46
|
+
|
47
|
+
You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
48
|
+
|
49
|
+
# You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
50
|
+
# You must cause any modified files to carry prominent notices stating that You changed the files; and
|
51
|
+
# You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
52
|
+
# If the Work includes a __NOTICE__ text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
53
|
+
|
54
|
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
55
|
+
|
56
|
+
<notextile></div><div class="toggle"></notextile>
|
57
|
+
|
58
|
+
h2. 5. Submission of Contributions.
|
59
|
+
|
60
|
+
Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
61
|
+
|
62
|
+
<notextile></div><div class="toggle"></notextile>
|
63
|
+
|
64
|
+
h2. 6. Trademarks.
|
65
|
+
|
66
|
+
This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
67
|
+
|
68
|
+
<notextile></div><div class="toggle"></notextile>
|
69
|
+
|
70
|
+
h2. 7. Disclaimer of Warranty.
|
71
|
+
|
72
|
+
Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an **AS IS** BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
73
|
+
|
74
|
+
<notextile></div><div class="toggle"></notextile>
|
75
|
+
|
76
|
+
h2. 8. Limitation of Liability.
|
77
|
+
|
78
|
+
In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
79
|
+
|
80
|
+
<notextile></div><div class="toggle"></notextile>
|
81
|
+
|
82
|
+
h2. 9. Accepting Warranty or Additional Liability.
|
83
|
+
|
84
|
+
While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
85
|
+
|
86
|
+
END OF TERMS AND CONDITIONS
|
87
|
+
|
88
|
+
<notextile></div><div class="toggle"></notextile>
|
89
|
+
|
90
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
|
91
|
+
|
92
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
93
|
+
|
94
|
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an **AS IS** BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
|
95
|
+
|
96
|
+
<notextile></div></notextile>
|
data/README.textile
CHANGED
@@ -9,8 +9,31 @@ h3. BUGS:
|
|
9
9
|
|
10
10
|
h3. Example
|
11
11
|
|
12
|
-
|
12
|
+
Let's define a super-simple twitter user and status model:
|
13
13
|
|
14
|
+
<pre><code>
|
15
|
+
User = Struct.new(
|
16
|
+
:id, :screen_name, :protected, :followers_count, :friends_count, :statuses_count, :favourites_count, :created_at,
|
17
|
+
:name, :url, :location, :description, :time_zone, :utc_offset,
|
18
|
+
:profile_background_color, :profile_text_color, :profile_link_color, :profile_sidebar_border_color, :profile_sidebar_fill_color, :profile_background_tile, :profile_background_image_url, :profile_image_url
|
19
|
+
)
|
20
|
+
|
21
|
+
Status = Struct.new( :id, :created_at, :user, :favorited, :truncated,
|
22
|
+
:in_reply_to_user_id, :in_reply_to_status_id, :text, :source,
|
23
|
+
:in_reply_to_screen_name )
|
24
|
+
</code></pre>
|
25
|
+
|
26
|
+
With no other work, we can pull a raw JSON hash off the wire and create model instances:
|
27
|
+
|
28
|
+
<pre><code>
|
29
|
+
raw_json_resp = RestClient.get("http://twitter.com/statuses/show/12233609555.json")
|
30
|
+
Twitter::Status.adapt(JSON.load(raw_json_resp.to_s))
|
31
|
+
#=> #<struct Titi::Provider::Twitter::Status id=12233609555, created_at="Thu Apr 15 17:01:52 +0000 2010", user=#<struct Titi::Provider::Twitter::User id=1468401, screen_name="sockington", protected=false, followers_count=1520814, friends_count=457, statuses_count=6234, favourites_count=2, created_at=Mon, 19 Mar 2007 03:45:00 +0000, name="Sockamillion", url="http://www.sockington.org/", location="Waltham, MA", description="I am Jason Scott's Cat.", time_zone="Eastern Time (US & Canada)", utc_offset=-18000, profile_background_color="48484c", profile_text_color="000000", profile_link_color="000000", profile_sidebar_border_color="79c021", profile_sidebar_fill_color="585e7e", profile_background_tile=false, profile_background_image_url="http://a1.twimg.com/profile_background_images/6682718/SocksTwitter.jpg", profile_image_url="http://a3.twimg.com/profile_images/77537329/IMG_3738_normal.JPG">, favorited=false, truncated=false, in_reply_to_user_id=nil, in_reply_to_status_id=nil, text="THANK GOODNESS THE LIBRARY OF CONGRESS HAS UNDERSTOOD THE IMPORTANCE OF MY TWEETS what do you mean others are getting in too", source="<a href=\"http://apiwiki.twitter.com/\" rel=\"nofollow\">API</a>", in_reply_to_screen_name=nil>
|
32
|
+
</code></pre>
|
33
|
+
|
34
|
+
Titi lets you write a straightforward and compact adaptor to activity stream format:
|
35
|
+
|
36
|
+
<pre><code>
|
14
37
|
class Titi::Provider::Twitter::Status
|
15
38
|
def to_activity_stream_entry
|
16
39
|
ActivityStreams::Entry.adapt(
|
@@ -30,12 +53,19 @@ h3. Example
|
|
30
53
|
end
|
31
54
|
end
|
32
55
|
end
|
33
|
-
|
56
|
+
end
|
57
|
+
</code></pre>
|
58
|
+
|
59
|
+
|
60
|
+
Where the mapping is direct, you can use an attribute => attribute hash, as shown in the call to ActivityStreams::Entry.adapt. For anything more complex, you can run arbitrary code in the method's block _(the part within the do ... end segment)_
|
61
|
+
|
62
|
+
Here's example output. _note: this isn't canonical activity streams format: the XML serialization needs work._
|
63
|
+
|
64
|
+
<pre><code>
|
34
65
|
tweet = Twitter::Status.get(12233609555)
|
35
66
|
entry = tweet.to_activity_stream_entry
|
36
|
-
|
37
67
|
puts entry.to_xml
|
38
|
-
|
68
|
+
|
39
69
|
<?xml version="1.0" encoding="UTF-8"?>
|
40
70
|
<entry>
|
41
71
|
<verb type="symbol">post</verb>
|
@@ -71,24 +101,8 @@ h3. Example
|
|
71
101
|
<source nil="true"></source>
|
72
102
|
<updated nil="true"></updated>
|
73
103
|
</entry>
|
104
|
+
</code></pre>
|
74
105
|
|
106
|
+
h2. Copyright
|
75
107
|
|
76
|
-
|
77
|
-
|
78
|
-
{"truncated"=>false, "favorited"=>false, "created_at"=>"Thu Apr 15 17:01:52 +0000 2010", "text"=>"THANK GOODNESS THE LIBRARY OF CONGRESS HAS UNDERSTOOD THE IMPORTANCE OF MY TWEETS what do you mean others are getting in too", "id"=>12233609555, "in_reply_to_user_id"=>nil, "in_reply_to_screen_name"=>nil, "source"=>"<a href=\"http://apiwiki.twitter.com/\" rel=\"nofollow\">API</a>", "user"=>#<struct Titi::Provider::Twitter::User id=1468401, screen_name="sockington", protected=false, followers_count=1520814, friends_count=457, statuses_count=6234, favourites_count=2, created_at=Mon, 19 Mar 2007 03:45:00 +0000, name="Sockamillion", url="http://www.sockington.org/", location="Waltham, MA", description="I am Jason Scott's Cat.", time_zone="Eastern Time (US & Canada)", utc_offset=-18000, profile_background_color="48484c", profile_text_color="000000", profile_link_color="000000", profile_sidebar_border_color="79c021", profile_sidebar_fill_color="585e7e", profile_background_tile=false, profile_background_image_url="http://a1.twimg.com/profile_background_images/6682718/SocksTwitter.jpg", profile_image_url="http://a3.twimg.com/profile_images/77537329/IMG_3738_normal.JPG">, "in_reply_to_status_id"=>nil}
|
79
|
-
</code></pre>
|
80
|
-
|
81
|
-
|
82
|
-
== Note on Patches/Pull Requests
|
83
|
-
|
84
|
-
* Fork the project.
|
85
|
-
* Make your feature addition or bug fix.
|
86
|
-
* Add tests for it. This is important so I don't break it in a
|
87
|
-
future version unintentionally.
|
88
|
-
* Commit, do not mess with rakefile, version, or history.
|
89
|
-
(if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
|
90
|
-
* Send me a pull request. Bonus points for topic branches.
|
91
|
-
|
92
|
-
== Copyright
|
93
|
-
|
94
|
-
Copyright (c) 2010 mrflip. See LICENSE for details.
|
108
|
+
Copyright (c) 2010 Infochimps, Inc. Available under Apache license: see LICENSE for details.
|
data/VERSION
CHANGED
@@ -1 +1 @@
|
|
1
|
-
0.0.
|
1
|
+
0.0.3
|
data/lib/titi.rb
CHANGED
@@ -0,0 +1,31 @@
|
|
1
|
+
require 'hpricot'
|
2
|
+
|
3
|
+
module Hpricot::IMWExtensions
|
4
|
+
def contents_of path
|
5
|
+
cnts = self.at path
|
6
|
+
cnts.inner_html if cnts
|
7
|
+
end
|
8
|
+
def path_attr path, attr
|
9
|
+
cnts = self.at path
|
10
|
+
cnts.attributes[attr] if cnts
|
11
|
+
end
|
12
|
+
def class_of path
|
13
|
+
self.path_attr_safely(path, 'class')
|
14
|
+
end
|
15
|
+
end
|
16
|
+
|
17
|
+
class Hpricot::Elem
|
18
|
+
include Hpricot::IMWExtensions
|
19
|
+
end
|
20
|
+
|
21
|
+
class Hpricot::Elements
|
22
|
+
include Hpricot::IMWExtensions
|
23
|
+
end
|
24
|
+
|
25
|
+
class Hpricot::Doc
|
26
|
+
include Hpricot::IMWExtensions
|
27
|
+
end
|
28
|
+
|
29
|
+
class Hpricot::BogusETag
|
30
|
+
include Hpricot::IMWExtensions
|
31
|
+
end
|
@@ -0,0 +1,387 @@
|
|
1
|
+
#
|
2
|
+
# h2. lib/imw/parsers/html_parser.rb -- html parser
|
3
|
+
#
|
4
|
+
# == About
|
5
|
+
#
|
6
|
+
# h4. HTML Extractor
|
7
|
+
#
|
8
|
+
# * map repeating HTML elements to intermediate ruby data structure
|
9
|
+
# * optimize all the common cases for expressive brevity
|
10
|
+
# * output structure will come from HTML structure; map to desired output objects in transform stage.
|
11
|
+
# * spec shouldn't be allowed to get too much more complicated than this; again, transform stage exists
|
12
|
+
#
|
13
|
+
# If this doesn't yield satisfaction you may enjoy
|
14
|
+
# * http://blog.labnotes.org/2006/07/11/scraping-with-style-scrapi-toolkit-for-ruby/
|
15
|
+
# * http://scrubyt.org/
|
16
|
+
# Note of course that these have quite different goals. For example, we don't
|
17
|
+
# have any interest in "interactive" crawling, eg form submission, or at least
|
18
|
+
# that goes elsewhere.
|
19
|
+
#
|
20
|
+
#
|
21
|
+
# == Sample HTML (http://twitter.com):
|
22
|
+
#
|
23
|
+
# <ul class="about vcard entry-author">
|
24
|
+
# <li ><span class="label">Name</span> <span class="fn" >MarsPhoenix </span> </li>
|
25
|
+
# <li ><span class="label">Location</span> <span class="adr">Mars, Solar System</span> </li>
|
26
|
+
# <li id="bio"><span class="label">Bio</span> <span class="bio">I dig Mars! </span> </li>
|
27
|
+
# <li ><span class="label">Web</span>
|
28
|
+
# <a href="http://tinyurl.com/5wwaru" class="url" rel="me nofollow">http://tinyurl.co...</a></li>
|
29
|
+
# </ul>
|
30
|
+
#
|
31
|
+
# == Parser Spec:
|
32
|
+
# :hcard => m_one('//ul.vcard.about',
|
33
|
+
# {
|
34
|
+
# :name => 'li/span.fn',
|
35
|
+
# :location => 'li/span.adr',
|
36
|
+
# :url => m_attr('li/a.url[@href]', 'href'),
|
37
|
+
# :bio => 'li#bio/span.bio',
|
38
|
+
# }
|
39
|
+
# )
|
40
|
+
#
|
41
|
+
# == Example return:
|
42
|
+
# { :hcard => { :name => 'Mars Phoenix', :location => 'Mars, Solar System', :bio => 'I dig Mars!', :url => 'http://tinyurl.com/5wwaru' } }
|
43
|
+
#
|
44
|
+
# == Sample HTML (http://delicious.com):
|
45
|
+
# <ul id="bookmarklist" class="bookmarks NOTHUMB">
|
46
|
+
# <li class="post" id="item-...">
|
47
|
+
# <div class="bookmark NOTHUMB">
|
48
|
+
# <div class="dateGroup"> <span title="23 APR 08">23 APR 08</span> </div>
|
49
|
+
# <div class="data">
|
50
|
+
# <h4> <a rel="nofollow" class="taggedlink" href="http://www.cs.biu.ac.il/~koppel/BlogCorpus.htm">Blog Authorship Corpus (Blogger.com 1994)</a>
|
51
|
+
# <a class="inlinesave" href="...">SAVE</a> </h4>
|
52
|
+
# <h5 class="savers-label"> PEOPLE</h5>
|
53
|
+
# <div class="savers savers2"> <a class="delNav" href="/url/7df6661946fca61863312644eb071953"><span class="delNavCount">26</span></a> </div>
|
54
|
+
# <div class="description"> The Blog Authorship Corpus consists of the collected posts of 19,320 bloggers gathered from blogger.com in August 2004. The corpus incorporates a total of 681,288 posts and over 140 million words - or approximately 35 posts and 7250 words per person. </div>
|
55
|
+
# </div>
|
56
|
+
# <div class="meta"></div>
|
57
|
+
# <h5 class="tag-chain-label">TAGS</h5>
|
58
|
+
# <div class="tagdisplay">
|
59
|
+
# <ul class="tag-chain">
|
60
|
+
# <li class="tag-chain-item off first"><a class="tag-chain-item-link" rel="tag" href="/infochimps/blog" ><span class="tag-chain-item-span">blog</span> </a></li>
|
61
|
+
# <li class="tag-chain-item off"> <a class="tag-chain-item-link" rel="tag" href="/infochimps/corpus" ><span class="tag-chain-item-span">corpus</span> </a></li>
|
62
|
+
# <li class="tag-chain-item off"> <a class="tag-chain-item-link" rel="tag" href="/infochimps/analysis" ><span class="tag-chain-item-span">analysis</span></a></li>
|
63
|
+
# <li class="tag-chain-item off"> <a class="tag-chain-item-link" rel="tag" href="/infochimps/nlp" ><span class="tag-chain-item-span">nlp</span> </a></li>
|
64
|
+
# <li class="tag-chain-item on last"> <a class="tag-chain-item-link" rel="tag" href="/infochimps/dataset" ><span class="tag-chain-item-span">dataset</span> </a></li>
|
65
|
+
# </ul>
|
66
|
+
# </div>
|
67
|
+
# <div class="clr"></div>
|
68
|
+
# </div>
|
69
|
+
# </li>
|
70
|
+
# </ul>
|
71
|
+
#
|
72
|
+
# == Parser Specification:
|
73
|
+
# :bookmarks => [ 'ul#bookmarklist/li.post/.bookmark',
|
74
|
+
# {
|
75
|
+
# :date => hash( '.dateGroup/span',
|
76
|
+
# [:year, :month, :day] => regexp( '', /(\d{2}) ([A-Z]{3}) (\d{2})/),
|
77
|
+
# ),
|
78
|
+
# :title => '.data/h4/a.taggedlink',
|
79
|
+
# :url => attr( '.data/h4/a.taggedlink', 'href'),
|
80
|
+
# :del_link_url => href( '.data/.savers/a.delNav),
|
81
|
+
# :num_savers => to_i( '.data/.savers//span.delNavCount'),
|
82
|
+
# :description => '.data/.description',
|
83
|
+
# :tags => ['.tagdisplay//tag-chain-item-span']
|
84
|
+
# }
|
85
|
+
# ]
|
86
|
+
#
|
87
|
+
# == Example output:
|
88
|
+
# { :bookmarks => [
|
89
|
+
# { :date => { :year => '08', :month => 'APR', :day => '23' },
|
90
|
+
# :title => 'Blog Authorship Corpus (Blogger.com 1994)',
|
91
|
+
# :url => 'http://www.cs.biu.ac.il/~koppel/BlogCorpus.htm',
|
92
|
+
# :del_link_url => '/url/7df6661946fca61863312644eb071953',
|
93
|
+
# :num_savers => 26,
|
94
|
+
# :description => 'The Blog ... ',
|
95
|
+
# :tags => ['blog', 'corpus', 'analysis', 'nlp', 'dataset'],
|
96
|
+
# }
|
97
|
+
# ]}
|
98
|
+
#
|
99
|
+
# == Implementation:
|
100
|
+
#
|
101
|
+
# Internally, we take the spec and turn it into a recursive structure of Matcher
|
102
|
+
# objects. These consume Hpricot Elements and return the appropriately extracted
|
103
|
+
# object.
|
104
|
+
#
|
105
|
+
# Note that the /default/ is for a bare selector to match ONE element, and to not
|
106
|
+
# complain if there are many.
|
107
|
+
#
|
108
|
+
# Missing elements are silently ignored -- for example if
|
109
|
+
# :foo => 'li.missing'
|
110
|
+
# there will simply be no :foo element in the hash (as opposed to having hsh[:foo]
|
111
|
+
# set to nil -- hsh.include?(foo) will be false)
|
112
|
+
#
|
113
|
+
#
|
114
|
+
# == List of Matchers:
|
115
|
+
# { :field => /spec/, ... } # hash hash, each field taken from spec.
|
116
|
+
# [ "hpricot_path" ] # 1-el array array: for each element matching
|
117
|
+
# hpricot_path, the inner_html
|
118
|
+
# [ "hpricot_path", /spec/ ] # 2-el array array: for each element matching
|
119
|
+
# hpricot_path, pass to spec
|
120
|
+
# "hpricot_path" # string same as one("hpricot_path")
|
121
|
+
# one("hpricot_path") # one first match to hpricot_path
|
122
|
+
# one("hpricot_path", /spec/) # one applies spec to first match to hpricot_path
|
123
|
+
# (these all match on one path:)
|
124
|
+
# regexp("hpricot_path", /RE/) # regexp capture groups from matching RE against
|
125
|
+
# inner_html of first match to hpricot_path
|
126
|
+
# attr("hpricot_path", 'attr_name') # attr
|
127
|
+
# href("hpricot_path") # href shorthand for attr(foo, 'href')
|
128
|
+
# no_html # strip tags from contents
|
129
|
+
# html_encoded # html encode contents
|
130
|
+
# to_i, to_f, etc # convert
|
131
|
+
# lambda{|doc| ... } # proc calls proc on current doc
|
132
|
+
#
|
133
|
+
# == Complicated HCard example:
|
134
|
+
# :hcards => [ '//ul.users/li.vcard',
|
135
|
+
# {
|
136
|
+
# :name => '.fn',
|
137
|
+
# :address => one('.adr',
|
138
|
+
# :street => '.street',
|
139
|
+
# :city => '.city',
|
140
|
+
# :zip => '.postal'
|
141
|
+
# )
|
142
|
+
# :tel => [ 'span.tel',
|
143
|
+
# {
|
144
|
+
# :type => 'span.type',
|
145
|
+
# [:cc, :area, :num] => hp.regexp('span.value', /+(\d+).(\d{3})-(\d{3}-\d{4})/),
|
146
|
+
# }
|
147
|
+
# ]
|
148
|
+
# :tags => [ '.tag' ],
|
149
|
+
# }
|
150
|
+
# ]
|
151
|
+
#
|
152
|
+
# == Resulting Parser
|
153
|
+
# MatchHash({:hcards => MatchArray('//ul.users/li.hcard',
|
154
|
+
# MatchHash({
|
155
|
+
# :name => MatchFirst('.fn'),
|
156
|
+
# :address => MatchFirst('.adr',
|
157
|
+
# MatchHash({
|
158
|
+
# :street => MatchFirst('.street'),
|
159
|
+
# :city => MatchFirst('.locality),
|
160
|
+
# :state => MatchFirst('.region),
|
161
|
+
# :zip => MatchFirst('.postal'),
|
162
|
+
# }))
|
163
|
+
# :tel => MatchArray('span.tel',
|
164
|
+
# MatchHash({
|
165
|
+
# :type => MatchFirst('span.type'),
|
166
|
+
# [:cc, :area, :num] => RegexpMatcher('span.value', /+(\d+).(\d{3})-(\d{3}-\d{4})/),
|
167
|
+
# })
|
168
|
+
# )
|
169
|
+
# :tags => MatchArray('.tag'),
|
170
|
+
# })
|
171
|
+
# )
|
172
|
+
#
|
173
|
+
# == Example output
|
174
|
+
# [
|
175
|
+
# {:tel => [ {:type => 'home', :cc => '49', :area => '305', :num => '555-1212'},
|
176
|
+
# {:type => 'work', :cc => '49', :area => '305', :num => '555-6969'}, ],
|
177
|
+
# :name => "Bob Dobbs, Jr.",
|
178
|
+
# :tags => ["church"] },
|
179
|
+
# {:tel => [ {:type => 'fax', :cc => '49', :area => '305', :num => '867-5309'}, ],
|
180
|
+
# :name => "Jenny",
|
181
|
+
# :address => { :street => "53 Evergreen Terr.", :city => "Springfield" },
|
182
|
+
# :tags => ["bathroom", "wall"] },
|
183
|
+
# ]
|
184
|
+
#
|
185
|
+
# Author:: (Philip flip Kromer, Dhruv Bansal) for Infinite Monkeywrench Project (mailto:coders@infochimps.org)
|
186
|
+
# Copyright:: Copyright (c) 2008 infochimps.org
|
187
|
+
# License:: GPL 3.0
|
188
|
+
# Website:: http://infinitemonkeywrench.org/
|
189
|
+
#
|
190
|
+
# puts "#{File.basename(__FILE__)}: Something clever" # at bottom
|
191
|
+
|
192
|
+
require 'imw/parsers/html_parser/matchers'
|
193
|
+
|
194
|
+
module IMW
|
195
|
+
module Parsers
|
196
|
+
class HtmlParser
|
197
|
+
|
198
|
+
include IMW::Parsers::HtmlMatchers
|
199
|
+
|
200
|
+
attr_accessor :parse_tree
|
201
|
+
|
202
|
+
#
|
203
|
+
# Parse Tree
|
204
|
+
#
|
205
|
+
def initialize arg_spec=nil
|
206
|
+
spec = arg_spec || self.class.parser_spec
|
207
|
+
self.parse_tree = IMW::Parsers::HtmlMatchers.build_parse_tree(spec)
|
208
|
+
end
|
209
|
+
|
210
|
+
#
|
211
|
+
# See IMW::HtmlParser for syntax
|
212
|
+
#
|
213
|
+
#
|
214
|
+
def self.parser_spec
|
215
|
+
raise "Override this to create your own parser spec"
|
216
|
+
end
|
217
|
+
|
218
|
+
#
|
219
|
+
# Walk
|
220
|
+
#
|
221
|
+
def parse doc
|
222
|
+
self.parse_tree.match(doc)
|
223
|
+
end
|
224
|
+
|
225
|
+
# one("hpricot_path") first match to hpricot_path
|
226
|
+
# one("hpricot_path", /spec/) applies spec to first match to hpricot_path
|
227
|
+
#
|
228
|
+
def self.one selector, matcher
|
229
|
+
MatchFirstElement.new(selector, IMW::Parsers::HtmlMatchers.build_parse_tree(matcher))
|
230
|
+
end
|
231
|
+
# match the +attr+ attribute of the first element given by +selector+
|
232
|
+
def self.attr selector, attr, matcher=nil
|
233
|
+
MatchAttribute.new(selector, attr, IMW::Parsers::HtmlMatchers.build_parse_tree(matcher))
|
234
|
+
end
|
235
|
+
# shorthand for +attr(foo, 'href')+
|
236
|
+
def self.href selector, matcher=nil
|
237
|
+
self.attr(selector, 'href', matcher)
|
238
|
+
end
|
239
|
+
# shorthand for +attr(foo, 'src')+
|
240
|
+
def self.src selector, matcher=nil
|
241
|
+
self.attr(selector, 'src', matcher)
|
242
|
+
end
|
243
|
+
|
244
|
+
def self.proc selector, proc, matcher=nil
|
245
|
+
MatchProc.new(selector, proc, IMW::Parsers::HtmlMatchers.build_parse_tree(matcher))
|
246
|
+
end
|
247
|
+
|
248
|
+
# strip ","s (!! thus disrespecting locale !!!)
|
249
|
+
# and convert to int
|
250
|
+
def self.to_num selector, matcher=nil
|
251
|
+
proc selector, lambda{|num| num.to_s.gsub(/,/,'').to_i if num }, matcher
|
252
|
+
end
|
253
|
+
def self.to_json selector, matcher=nil
|
254
|
+
proc selector, lambda{|v| v.to_json if v }, matcher
|
255
|
+
end
|
256
|
+
|
257
|
+
def self.strip selector, matcher=nil
|
258
|
+
proc selector, lambda{|v| v.strip }, matcher
|
259
|
+
end
|
260
|
+
|
261
|
+
def self.re_group selector, re
|
262
|
+
MatchRegexp.new(selector, re)
|
263
|
+
end
|
264
|
+
def self.re selector, re
|
265
|
+
MatchRegexp.new(selector, re, nil, :capture => 1)
|
266
|
+
end
|
267
|
+
def self.re_all selector, re, matcher=nil
|
268
|
+
MatchRegexpRepeatedly.new(selector, re)
|
269
|
+
end
|
270
|
+
|
271
|
+
# def self.plain_text selector, matcher=nil
|
272
|
+
# proc selector, lambda{|el| el.inner_text if el }, matcher
|
273
|
+
# end
|
274
|
+
|
275
|
+
# attr_accessor :mapping
|
276
|
+
#
|
277
|
+
# #
|
278
|
+
# # Feed me a hash and I'll semantify HTML
|
279
|
+
# #
|
280
|
+
# # The hash should magically adhere to the too-complicated,
|
281
|
+
# # ever evolving goatrope that works for the below
|
282
|
+
# #
|
283
|
+
# #
|
284
|
+
# def initialize mapping
|
285
|
+
# self.mapping = mapping
|
286
|
+
# end
|
287
|
+
#
|
288
|
+
# #
|
289
|
+
# # take a document subtree,
|
290
|
+
# # and a mapping of hpricot paths to that subtree's data mapping
|
291
|
+
# # recursively extract that datamapping
|
292
|
+
# #
|
293
|
+
# def extract_tree hdoc, content, sub_mapping
|
294
|
+
# data = { }
|
295
|
+
# sub_mapping.each do |selector, target|
|
296
|
+
# data[selector] = []
|
297
|
+
# sub_contents = content/selector
|
298
|
+
# sub_contents.each do |sub_content|
|
299
|
+
# sub_data = {}
|
300
|
+
# extract_node hdoc, sub_content, sub_data, selector, target
|
301
|
+
# data[selector] << sub_data
|
302
|
+
# end
|
303
|
+
# end
|
304
|
+
# data
|
305
|
+
# # end
|
306
|
+
# # if selector.is_a?(String)
|
307
|
+
# # conts = (content)
|
308
|
+
# # else
|
309
|
+
# # conts = [content]
|
310
|
+
# # end
|
311
|
+
# # conts[0..0].each do |content|
|
312
|
+
# # extract_node hdoc, content, data, selector, target
|
313
|
+
# # end
|
314
|
+
# # end
|
315
|
+
# data
|
316
|
+
# end
|
317
|
+
#
|
318
|
+
# #
|
319
|
+
# # insert the extracted element into the data mapping
|
320
|
+
# #
|
321
|
+
# def extract_node hdoc, content, data, selector, target
|
322
|
+
# classification = classify_node(selector, target)
|
323
|
+
# result = \
|
324
|
+
# case classification
|
325
|
+
# when :subtree
|
326
|
+
# target.each do |sub_selector, sub_target|
|
327
|
+
# extract_node hdoc, content, data, sub_selector, sub_target
|
328
|
+
# end
|
329
|
+
#
|
330
|
+
# when :sub_attribute
|
331
|
+
# k, v = selector.to_a[0]
|
332
|
+
# subcontent = (k[0..0] == '/') ? (hdoc.at(k)) : (content.at(k))
|
333
|
+
# val = subcontent.attributes[v.to_s] if subcontent
|
334
|
+
# data[target] = val unless val.blank?
|
335
|
+
#
|
336
|
+
# when :attribute then
|
337
|
+
# val = content.attributes[selector.to_s]
|
338
|
+
# data[target] = val unless val.blank?
|
339
|
+
#
|
340
|
+
# when :flatten_list
|
341
|
+
# subcontents = (selector[0..0] == '/') ? (hdoc/selector) : (content/selector)
|
342
|
+
# data[target.first] = subcontents.map{|subcontent| subcontent.inner_html }
|
343
|
+
#
|
344
|
+
# when :inner_html
|
345
|
+
# subcontent = (selector[0..0] == '/') ? (hdoc.at(selector)) : (content.at(selector))
|
346
|
+
# data[target] = subcontent.inner_html.strip if subcontent
|
347
|
+
#
|
348
|
+
# else
|
349
|
+
# raise "classify_node shouldn't ever return #{classification}"
|
350
|
+
# end
|
351
|
+
# # puts "%-19s %-19s %-31s %s" % [target.inspect[0..18], classification.inspect[0..18], selector.inspect[0..30], result.inspect[0..90]] if (classification == :sub_attribute)
|
352
|
+
# # puts '' if classification == :subtree
|
353
|
+
# end
|
354
|
+
#
|
355
|
+
# def classify_node selector, target
|
356
|
+
# case
|
357
|
+
# when target.is_a?(Hash) then :subtree
|
358
|
+
# when selector.is_a?(Hash) && (selector.length == 1) then
|
359
|
+
# k, v = selector.to_a[0]
|
360
|
+
# case v
|
361
|
+
# when Symbol then :sub_attribute
|
362
|
+
# end
|
363
|
+
# when selector.is_a?(Symbol) then :attribute
|
364
|
+
# when selector.is_a?(String) && target.is_a?(Array) then :flatten_list
|
365
|
+
# when selector.is_a?(String) && target.is_a?(Symbol) then :inner_html
|
366
|
+
# else
|
367
|
+
# raise "Can't classify mapping: " + [selector, target].join(" - ")
|
368
|
+
# end
|
369
|
+
# end
|
370
|
+
#
|
371
|
+
# # use #mapping to parse file
|
372
|
+
# def parse link
|
373
|
+
# begin hdoc = Hpricot(link.contents)
|
374
|
+
# rescue; warn "can't hpricot #{link.to_s}" ; return false; end
|
375
|
+
# raw_taggings = extract_tree hdoc, hdoc, self.mapping
|
376
|
+
# end
|
377
|
+
#
|
378
|
+
# # use #mapping to parse file
|
379
|
+
# def parse_file filename
|
380
|
+
# begin hdoc = Hpricot(File.open(filename))
|
381
|
+
# rescue; warn "can't hpricot #{filename}" ; return false; end
|
382
|
+
# raw_taggings = extract_tree hdoc, hdoc, self.mapping
|
383
|
+
# end
|
384
|
+
end
|
385
|
+
end
|
386
|
+
end
|
387
|
+
|
@@ -0,0 +1,254 @@
|
|
1
|
+
module Titi
|
2
|
+
module Matcher
|
3
|
+
# An abstract class from which to subclass specific HTML matchers.
|
4
|
+
#
|
5
|
+
# A subclass is initialized with a +selector+ and an optional
|
6
|
+
# +matcher+. The +selector+ is an HTML path specification used to
|
7
|
+
# collect elements from the document. If initialized with a
|
8
|
+
# +matcher+, the +matcher+ is used to return match information
|
9
|
+
# from the elements; else the inner HTML is returned. Subclasses
|
10
|
+
# decide how the +selector+ will collect elements.
|
11
|
+
class Base
|
12
|
+
|
13
|
+
attr_accessor :selector
|
14
|
+
attr_accessor :matcher
|
15
|
+
attr_accessor :options
|
16
|
+
|
17
|
+
def initialize selector, matcher=nil, options={}
|
18
|
+
self.selector = selector
|
19
|
+
self.matcher = matcher
|
20
|
+
self.options = options
|
21
|
+
end
|
22
|
+
|
23
|
+
def match doc
|
24
|
+
raise "Abstract class #{self.class}"
|
25
|
+
end
|
26
|
+
|
27
|
+
end
|
28
|
+
|
29
|
+
# Concrete subclass of <tt>IMW::Parsers::HtmlMatchers::Matcher</tt>
|
30
|
+
# for matching against the first element of a document matching a
|
31
|
+
# selector.
|
32
|
+
class MatchFirstElement < Titi::Matcher::Base
|
33
|
+
# Grab the first element from +doc+ matching the +selector+ this
|
34
|
+
# class was initialized with. If initialized with a +matcher+,
|
35
|
+
# then return the +matcher+'s match against the first element,
|
36
|
+
# else just return the inner HTML of the first element.
|
37
|
+
#
|
38
|
+
# m = MatchFirstElement.new('span#bio/a.homepage')
|
39
|
+
# m.match('<span id="bio"><a class="homepage" href="http://foo.bar">My Homepage</a></span>')
|
40
|
+
# # => 'My Homepage'
|
41
|
+
def match doc
|
42
|
+
doc = Hpricot(doc) if doc.is_a?(String)
|
43
|
+
el = doc.at(selector) or return nil
|
44
|
+
if matcher
|
45
|
+
matcher.match(el)
|
46
|
+
else
|
47
|
+
options[:html] ? el : el.inner_text.strip
|
48
|
+
end
|
49
|
+
end
|
50
|
+
end
|
51
|
+
|
52
|
+
# FIXME is there really a need for this separate class? why can't
|
53
|
+
# MatchFirstElement.match accept a block?
|
54
|
+
class MatchProc < MatchFirstElement
|
55
|
+
attr_accessor :proc
|
56
|
+
attr_accessor :options
|
57
|
+
def initialize selector, proc, matcher=nil, options={}
|
58
|
+
super selector, matcher
|
59
|
+
self.options = options
|
60
|
+
self.proc = proc
|
61
|
+
end
|
62
|
+
def match doc
|
63
|
+
val = super doc
|
64
|
+
val ? self.proc.call(val) : self.proc.call(doc)
|
65
|
+
end
|
66
|
+
end
|
67
|
+
|
68
|
+
# Concrete subclass of <tt>IMW::Parsers::HtmlMatchers::Matcher</tt>
|
69
|
+
# for matching each element of a document matching a selector.
|
70
|
+
class MatchArray < Titi::Matcher::Base
|
71
|
+
# Grab each element from +doc+ matching the +selector+ this
|
72
|
+
# class was initialized with. If initialized with a +matcher+,
|
73
|
+
# then return an array consisting of the +matcher+'s match
|
74
|
+
# against each element, else just return an array consisting of
|
75
|
+
# the inner HTML of each element.
|
76
|
+
#
|
77
|
+
# m = MatchArray.new('span#bio/a.homepage')
|
78
|
+
# m.match('<span id="bio"><a class="homepage" href="http://foo.bar">My Homepage</a></span>
|
79
|
+
# <span id="bio"><a class="homepage" href="http://foo.baz">Your Homepage</a></span>
|
80
|
+
# <span id="bio"><a class="homepage" href="http://foo.qux">Their Homepage</a></span>')
|
81
|
+
# # => ["My Homepage", "Your Homepage", "Their Homepage"]
|
82
|
+
def match doc
|
83
|
+
doc = Hpricot(doc) if doc.is_a?(String)
|
84
|
+
subdoc = (doc/selector) or return nil
|
85
|
+
if matcher
|
86
|
+
subdoc.map{|el| matcher.match(el)}
|
87
|
+
else
|
88
|
+
if options[:html]
|
89
|
+
subdoc.map{|el| el }
|
90
|
+
else
|
91
|
+
subdoc.map{|el| el.inner_text.strip }
|
92
|
+
end
|
93
|
+
end
|
94
|
+
end
|
95
|
+
end
|
96
|
+
|
97
|
+
# Concrete subclass of <tt>IMW::Parsers::HtmlMatchers::Matcher</tt>
|
98
|
+
# for matching an attribute of the first element of a document
|
99
|
+
# matching a selector.
|
100
|
+
class MatchAttribute < Titi::Matcher::Base
|
101
|
+
|
102
|
+
attr_accessor :attribute
|
103
|
+
|
104
|
+
# Unlike <tt>IMW::Parsers::HtmlMatchers::Matcher</tt>,
|
105
|
+
# <tt>IMW::Parsers::HtmlMatchers::MatchAttribute</tt> is initialized
|
106
|
+
# with three arguments: the +selector+ which collects elements
|
107
|
+
# from an HTML document, an +attribute+ to extract, and
|
108
|
+
# (optionally) a +matcher+ to perform the matching.
|
109
|
+
def initialize selector, attribute, matcher=nil
|
110
|
+
super selector, matcher
|
111
|
+
self.attribute = attribute.to_s
|
112
|
+
end
|
113
|
+
|
114
|
+
# Grab the first element from +doc+ matching the +selector+ this
|
115
|
+
# class was initialized with. If initialized with a +matcher+,
|
116
|
+
# then return the +matcher+'s match against the value of the
|
117
|
+
# +attribute+ this class was initialized with, else just return
|
118
|
+
# the value of the +attribute+.
|
119
|
+
#
|
120
|
+
# m = MatchAttribute.new('span#bio/a.homepage', 'href')
|
121
|
+
# m.match('<span id="bio"><a class="homepage" href="http://foo.bar">My Homepage</a></span>')
|
122
|
+
# # => 'http://foo.bar'
|
123
|
+
def match doc
|
124
|
+
doc = Hpricot(doc) if doc.is_a?(String)
|
125
|
+
val = doc.path_attr(selector, attribute)
|
126
|
+
matcher ? matcher.match(val) : val
|
127
|
+
end
|
128
|
+
end
|
129
|
+
|
130
|
+
# Concrete subclass of <tt>IMW::Parsers::HtmlMatchers::Matcher</tt>
|
131
|
+
# for using a regular expression to match against text in an HTML
|
132
|
+
# document.
|
133
|
+
class MatchRegexp < Titi::Matcher::Base
|
134
|
+
|
135
|
+
attr_accessor :re
|
136
|
+
attr_accessor :options
|
137
|
+
|
138
|
+
# Use the regular expression +re+ to return captures from the
|
139
|
+
# elements collected by +selector+ (treated as text) used on an
|
140
|
+
# HTML document (if +selector+ is +nil+ then match against the
|
141
|
+
# full text of the document). If the keyword argument
|
142
|
+
# <tt>:capture</tt> is specified then return the corresponding
|
143
|
+
# group (indexing is that of regular expressions; "1" is the
|
144
|
+
# first capture), else return an array of all captures. If
|
145
|
+
# +matcher+, then use it on the capture(s) before returning.
|
146
|
+
#
|
147
|
+
# FIXME Shouldn't the matcher come BEFORE the regexp capture,
|
148
|
+
# not after?
|
149
|
+
def initialize selector, re, matcher=nil, options={}
|
150
|
+
super selector, matcher
|
151
|
+
self.options = options
|
152
|
+
self.re = re
|
153
|
+
end
|
154
|
+
|
155
|
+
# Grab the first element from +doc+ matching the +selector+ this
|
156
|
+
# object was initialized with. Use the +re+ and the (optional)
|
157
|
+
# capture group this object was initialized with to capture a
|
158
|
+
# string (or array of strings if no capture group was specified)
|
159
|
+
# from the collected element (treated as text). If initialized
|
160
|
+
# with a +matcher+, then return the +matcher+'s match against
|
161
|
+
# the value of the capture(s), else just return the capture(s).
|
162
|
+
#
|
163
|
+
# m = MatchRegexp.new('span#bio/a.homepage', /Homepage of (.*)$/, nil, :capture => 1 )
|
164
|
+
# m.match('<span id="bio"><a class="homepage" href="http://foo.bar">Homepage of John Chimpo</a></span>')
|
165
|
+
# # => "John Chimpo"
|
166
|
+
def match doc
|
167
|
+
doc = Hpricot(doc) if doc.is_a?(String)
|
168
|
+
el = selector ? doc.contents_of(selector) : doc
|
169
|
+
m = re.match(el.to_s)
|
170
|
+
val = case
|
171
|
+
when m.nil? then nil
|
172
|
+
when self.options.key?(:capture) then m.captures[self.options[:capture] - 1] # -1 to match regexp indexing
|
173
|
+
else m.captures
|
174
|
+
end
|
175
|
+
# pass to matcher, if any
|
176
|
+
matcher ? matcher.match(val) : val
|
177
|
+
end
|
178
|
+
end
|
179
|
+
|
180
|
+
|
181
|
+
class MatchRegexpRepeatedly < Titi::Matcher::Base
|
182
|
+
attr_accessor :re
|
183
|
+
def initialize selector, re, matcher=nil
|
184
|
+
super selector, matcher
|
185
|
+
self.re = re
|
186
|
+
end
|
187
|
+
def match doc
|
188
|
+
doc = Hpricot(doc) if doc.is_a?(String)
|
189
|
+
# apply selector, if any
|
190
|
+
el = selector ? doc.contents_of(selector) : doc
|
191
|
+
return unless el
|
192
|
+
# get all matches
|
193
|
+
val = el.to_s.scan(re)
|
194
|
+
# if there's only one capture group, flatten the array
|
195
|
+
val = val.flatten if val.first && val.first.length == 1
|
196
|
+
# pass to matcher, if any
|
197
|
+
matcher ? matcher.match(val) : val
|
198
|
+
end
|
199
|
+
end
|
200
|
+
|
201
|
+
# Class for building a hash of values by using appropriate
|
202
|
+
# matchers against an HTML document.
|
203
|
+
class MatchHash
|
204
|
+
|
205
|
+
attr_accessor :match_hash
|
206
|
+
|
207
|
+
# The +match_hash+ must be a +Hash+ of symbols matched to HTML
|
208
|
+
# matchers (subclasses of
|
209
|
+
# <tt>IMW::Parsers::HtmlMatchers::Matcher</tt>).
|
210
|
+
def initialize match_hash
|
211
|
+
# Kludge? maybe.
|
212
|
+
raise "MatchHash requires a hash of :attributes => matchers." unless match_hash.is_a?(Hash)
|
213
|
+
self.match_hash = match_hash
|
214
|
+
end
|
215
|
+
|
216
|
+
# Use the +match_hash+ this +MatchHash+ was initialized with to
|
217
|
+
# select elements from +doc+ and extract information from them:
|
218
|
+
#
|
219
|
+
# m = MatchHash.new({
|
220
|
+
# :name => MatchFirstElement.new('li/span.customer'),
|
221
|
+
# :order_status => MatchAttribute.new('li/ul[@status]','status'),
|
222
|
+
# :products => MatchArray.new('li/ul/li')
|
223
|
+
# })
|
224
|
+
# m.match('<li><span class="customer">John Chimpo</span>
|
225
|
+
# <ul status="shipped">
|
226
|
+
# <li>bananas</li>
|
227
|
+
# <li>mangos</li>
|
228
|
+
# <li>banangos</li>
|
229
|
+
# </ul></li>')
|
230
|
+
# # => {
|
231
|
+
# :name => "John Chimpo",
|
232
|
+
# :order_status => "shipped",
|
233
|
+
# :products => ["bananas", "mangos", "banangos"]
|
234
|
+
# }
|
235
|
+
def match doc
|
236
|
+
doc = Hpricot(doc) if doc.is_a?(String)
|
237
|
+
hsh = { }
|
238
|
+
match_hash.each do |attr, m|
|
239
|
+
val = m.match(doc)
|
240
|
+
case attr
|
241
|
+
when Array then hsh.merge!(Hash.zip(attr, val).reject{|k,v| v.nil? }) if val
|
242
|
+
else hsh[attr] = val end
|
243
|
+
end
|
244
|
+
self.class.scrub!(hsh)
|
245
|
+
end
|
246
|
+
|
247
|
+
# kill off keys with nil values
|
248
|
+
def self.scrub! hsh
|
249
|
+
hsh # .reject{|k,v| v.nil? }
|
250
|
+
end
|
251
|
+
end
|
252
|
+
|
253
|
+
end
|
254
|
+
end
|
@@ -1,6 +1,5 @@
|
|
1
1
|
module Titi
|
2
2
|
module ParseTree
|
3
|
-
|
4
3
|
#
|
5
4
|
# construct the downstream part of a hash matcher
|
6
5
|
#
|
@@ -26,7 +25,8 @@ module Titi
|
|
26
25
|
MatchArray.new(spec[0].to_s, build_parse_tree(spec[1]))
|
27
26
|
when String then MatchFirstElement.new(spec)
|
28
27
|
when Proc then MatchProc.new(nil, spec)
|
29
|
-
when Regexp then MatchRegexp.new(nil, spec, nil, :
|
28
|
+
when Regexp then MatchRegexp.new(nil, spec, nil, :capture => 1)
|
29
|
+
when Symbol then MatchAttribute.new(nil, spec, nil)
|
30
30
|
else raise "Don't know how to parse #{spec.inspect}"
|
31
31
|
end
|
32
32
|
end
|
@@ -108,7 +108,6 @@ module Titi::Provider
|
|
108
108
|
#
|
109
109
|
def self.get status_id
|
110
110
|
raw_json_str = RestClient.get "http://twitter.com/statuses/show/#{status_id}.json"
|
111
|
-
# raw_json_str = %q{{"created_at":"Mon Mar 19 21:08:24 +0000 2007","profile_sidebar_fill_color":"ffffff","description":"Founder, http://infochimps.org - Building tools to Organize, Explore and Comprehend massive data sources","verified":false,"time_zone":"Central Time (US & Canada)","status":{"in_reply_to_status_id":null,"created_at":"Sat Apr 17 05:47:28 +0000 2010","favorited":false,"in_reply_to_user_id":null,"source":"<a href=\"http://www.atebits.com/\" rel=\"nofollow\">Tweetie</a>","id":12327261220,"in_reply_to_screen_name":null,"truncated":false,"text":"Hacking Activity Streams yay"},"following":null,"profile_sidebar_border_color":"f0edd8","url":"http://infochimps.org","profile_image_url":"http://a3.twimg.com/profile_images/377919497/FlipCircle-2009-900-trans_normal.png","notifications":null,"followers_count":1061,"profile_background_color":"BCC0C8","location":"iPhone: 30.316122,-97.733817","screen_name":"mrflip","profile_background_image_url":"http://a3.twimg.com/profile_background_images/2348065/2005Mar-AustinTypeTour-075_-_Rappers_Delight_Raindrop.jpg","friends_count":754,"statuses_count":1744,"profile_text_color":"000000","protected":false,"profile_background_tile":false,"favourites_count":98,"name":"Philip Flip Kromer","contributors_enabled":false,"profile_link_color":"0000ff","id":1554031,"lang":"en","geo_enabled":true,"utc_offset":-21600}}
|
112
111
|
raw_status = JSON.load(raw_json_str.to_s)
|
113
112
|
adapt(raw_status)
|
114
113
|
end
|
data/titi.gemspec
CHANGED
@@ -5,7 +5,7 @@
|
|
5
5
|
|
6
6
|
Gem::Specification.new do |s|
|
7
7
|
s.name = %q{titi}
|
8
|
-
s.version = "0.0.
|
8
|
+
s.version = "0.0.3"
|
9
9
|
|
10
10
|
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
|
11
11
|
s.authors = ["mrflip"]
|
@@ -13,21 +13,23 @@ Gem::Specification.new do |s|
|
|
13
13
|
s.description = %q{Facade adapting apis to activity streams spec}
|
14
14
|
s.email = %q{flip@infochimps.org}
|
15
15
|
s.extra_rdoc_files = [
|
16
|
-
"LICENSE",
|
16
|
+
"LICENSE.textile",
|
17
17
|
"README.textile"
|
18
18
|
]
|
19
19
|
s.files = [
|
20
20
|
".document",
|
21
21
|
".gitignore",
|
22
|
-
"LICENSE",
|
22
|
+
"LICENSE.textile",
|
23
23
|
"README.textile",
|
24
24
|
"Rakefile",
|
25
25
|
"VERSION",
|
26
26
|
"examples/twitter.rb",
|
27
27
|
"lib/titi.rb",
|
28
28
|
"lib/titi/adaptor.rb",
|
29
|
-
"lib/titi/
|
30
|
-
"lib/titi/
|
29
|
+
"lib/titi/ignore/hpricot.rb",
|
30
|
+
"lib/titi/ignore/html_parser.rb",
|
31
|
+
"lib/titi/ignore/matcher.rb",
|
32
|
+
"lib/titi/ignore/parse_tree.rb",
|
31
33
|
"lib/titi/provider.rb",
|
32
34
|
"lib/titi/provider/README.textile",
|
33
35
|
"lib/titi/provider/activity_streams.rb",
|
metadata
CHANGED
@@ -5,8 +5,8 @@ version: !ruby/object:Gem::Version
|
|
5
5
|
segments:
|
6
6
|
- 0
|
7
7
|
- 0
|
8
|
-
-
|
9
|
-
version: 0.0.
|
8
|
+
- 3
|
9
|
+
version: 0.0.3
|
10
10
|
platform: ruby
|
11
11
|
authors:
|
12
12
|
- mrflip
|
@@ -92,20 +92,22 @@ executables: []
|
|
92
92
|
extensions: []
|
93
93
|
|
94
94
|
extra_rdoc_files:
|
95
|
-
- LICENSE
|
95
|
+
- LICENSE.textile
|
96
96
|
- README.textile
|
97
97
|
files:
|
98
98
|
- .document
|
99
99
|
- .gitignore
|
100
|
-
- LICENSE
|
100
|
+
- LICENSE.textile
|
101
101
|
- README.textile
|
102
102
|
- Rakefile
|
103
103
|
- VERSION
|
104
104
|
- examples/twitter.rb
|
105
105
|
- lib/titi.rb
|
106
106
|
- lib/titi/adaptor.rb
|
107
|
-
- lib/titi/
|
108
|
-
- lib/titi/
|
107
|
+
- lib/titi/ignore/hpricot.rb
|
108
|
+
- lib/titi/ignore/html_parser.rb
|
109
|
+
- lib/titi/ignore/matcher.rb
|
110
|
+
- lib/titi/ignore/parse_tree.rb
|
109
111
|
- lib/titi/provider.rb
|
110
112
|
- lib/titi/provider/README.textile
|
111
113
|
- lib/titi/provider/activity_streams.rb
|
data/LICENSE
DELETED
@@ -1,20 +0,0 @@
|
|
1
|
-
Copyright (c) 2009 mrflip
|
2
|
-
|
3
|
-
Permission is hereby granted, free of charge, to any person obtaining
|
4
|
-
a copy of this software and associated documentation files (the
|
5
|
-
"Software"), to deal in the Software without restriction, including
|
6
|
-
without limitation the rights to use, copy, modify, merge, publish,
|
7
|
-
distribute, sublicense, and/or sell copies of the Software, and to
|
8
|
-
permit persons to whom the Software is furnished to do so, subject to
|
9
|
-
the following conditions:
|
10
|
-
|
11
|
-
The above copyright notice and this permission notice shall be
|
12
|
-
included in all copies or substantial portions of the Software.
|
13
|
-
|
14
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
15
|
-
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
16
|
-
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
17
|
-
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
18
|
-
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
19
|
-
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
20
|
-
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
data/lib/titi/matcher.rb
DELETED
@@ -1,157 +0,0 @@
|
|
1
|
-
module Titi
|
2
|
-
module Matcher
|
3
|
-
class Base
|
4
|
-
attr_accessor :selector
|
5
|
-
attr_accessor :matcher
|
6
|
-
def initialize selector, matcher=nil
|
7
|
-
self.selector = selector
|
8
|
-
self.matcher = matcher
|
9
|
-
end
|
10
|
-
def match doc
|
11
|
-
raise "Abstract class #{self.class}"
|
12
|
-
end
|
13
|
-
end
|
14
|
-
|
15
|
-
class MatchFirstElement < Base
|
16
|
-
# return the inner_html of the given element
|
17
|
-
#
|
18
|
-
# eg.
|
19
|
-
# m = MatchFirstElement.new('span#bio/a.homepage')
|
20
|
-
# m.match('<span id="bio"><a class="homepage" href="http://foo.bar">My Homepage</a></span>')
|
21
|
-
# # => 'My Homepage'
|
22
|
-
#
|
23
|
-
def match doc
|
24
|
-
el = doc.at(selector) or return nil
|
25
|
-
matcher ? matcher.match(el) : el.inner_html
|
26
|
-
end
|
27
|
-
end
|
28
|
-
|
29
|
-
class MatchArray < Base
|
30
|
-
# return the given element
|
31
|
-
#
|
32
|
-
# eg.
|
33
|
-
# m = MatchAttribute.new('span#bio/a.homepage', 'href')
|
34
|
-
# m.match('<span id="bio"><a class="homepage" href="http://foo.bar">My Homepage</a></span>')
|
35
|
-
# # => 'http://foo.bar'
|
36
|
-
#
|
37
|
-
def match doc
|
38
|
-
subdoc = (doc/selector) or return nil
|
39
|
-
if matcher
|
40
|
-
subdoc.map{|el| matcher.match(el)}
|
41
|
-
else
|
42
|
-
subdoc.map{|el| el.inner_html}
|
43
|
-
end
|
44
|
-
end
|
45
|
-
end
|
46
|
-
|
47
|
-
class MatchAttribute < Base
|
48
|
-
attr_accessor :attribute
|
49
|
-
def initialize selector, attribute, matcher=nil
|
50
|
-
super selector, matcher
|
51
|
-
self.attribute = attribute.to_s
|
52
|
-
end
|
53
|
-
# return the given attribute on the first matching path
|
54
|
-
#
|
55
|
-
# eg.
|
56
|
-
# m = MatchAttribute.new('span#bio/a.homepage', 'href')
|
57
|
-
# m.match('<span id="bio"><a class="homepage" href="http://foo.bar">My Homepage</a></span>')
|
58
|
-
# # => 'http://foo.bar'
|
59
|
-
#
|
60
|
-
def match doc
|
61
|
-
val = doc.path_attr(selector, attribute)
|
62
|
-
matcher ? matcher.match(val) : val
|
63
|
-
end
|
64
|
-
end
|
65
|
-
|
66
|
-
#
|
67
|
-
# map html elements -- or any HTMLParser tree -- to attributes in a hash.
|
68
|
-
# HTMLParser.new([ {
|
69
|
-
# :name => 'li/span.fn',
|
70
|
-
# :location => 'li/span.adr',
|
71
|
-
# :url => HTMLParser.attr('li/a.url[@href]', 'href'),
|
72
|
-
# :bio => 'li#bio/span.bio',
|
73
|
-
# }
|
74
|
-
# ])
|
75
|
-
#
|
76
|
-
class MatchHash
|
77
|
-
attr_accessor :match_hash
|
78
|
-
def initialize match_hash
|
79
|
-
# Kludge? maybe.
|
80
|
-
raise "MatchHash requires a hash of :attributes => matchers." unless match_hash.is_a?(Hash)
|
81
|
-
self.match_hash = match_hash
|
82
|
-
end
|
83
|
-
# Returns a hash mapping each attribute in match_hash
|
84
|
-
# to the result of its matcher on the current doc tree
|
85
|
-
def match doc
|
86
|
-
hsh = { }
|
87
|
-
match_hash.each do |attr, m|
|
88
|
-
val = m.match(doc)
|
89
|
-
case attr
|
90
|
-
when Array then hsh.merge!(Hash.zip(attr, val).reject{|k,v| v.nil? }) if val
|
91
|
-
else hsh[attr] = val end
|
92
|
-
end
|
93
|
-
self.class.scrub!(hsh)
|
94
|
-
end
|
95
|
-
# kill off keys with nil values
|
96
|
-
def self.scrub! hsh
|
97
|
-
hsh # .reject{|k,v| v.nil? }
|
98
|
-
end
|
99
|
-
end
|
100
|
-
|
101
|
-
class MatchProc < MatchFirstElement
|
102
|
-
attr_accessor :proc
|
103
|
-
attr_accessor :options
|
104
|
-
def initialize selector, proc, matcher=nil, options={}
|
105
|
-
super selector, matcher
|
106
|
-
self.options = options
|
107
|
-
self.proc = proc
|
108
|
-
end
|
109
|
-
def match doc
|
110
|
-
val = super doc
|
111
|
-
self.proc.call(val) if val
|
112
|
-
end
|
113
|
-
end
|
114
|
-
|
115
|
-
class MatchRegexp < Base
|
116
|
-
attr_accessor :re
|
117
|
-
attr_accessor :options
|
118
|
-
def initialize selector, re, matcher=nil, options={}
|
119
|
-
super selector, matcher
|
120
|
-
self.options = options
|
121
|
-
self.re = re
|
122
|
-
end
|
123
|
-
def match doc
|
124
|
-
# apply selector, if any
|
125
|
-
el = selector ? doc.contents_of(selector) : doc
|
126
|
-
m = re.match(el.to_s)
|
127
|
-
val = case
|
128
|
-
when m.nil? then nil
|
129
|
-
when self.options[:one] then m.captures.first
|
130
|
-
else m.captures
|
131
|
-
end
|
132
|
-
# pass to matcher, if any
|
133
|
-
matcher ? matcher.match(val) : val
|
134
|
-
end
|
135
|
-
end
|
136
|
-
|
137
|
-
class MatchRegexpRepeatedly < Base
|
138
|
-
attr_accessor :re
|
139
|
-
def initialize selector, re, matcher=nil
|
140
|
-
super selector, matcher
|
141
|
-
self.re = re
|
142
|
-
end
|
143
|
-
def match doc
|
144
|
-
# apply selector, if any
|
145
|
-
el = selector ? doc.contents_of(selector) : doc
|
146
|
-
return unless el
|
147
|
-
# get all matches
|
148
|
-
val = el.to_s.scan(re)
|
149
|
-
# if there's only one capture group, flatten the array
|
150
|
-
val = val.flatten if val.first && val.first.length == 1
|
151
|
-
# pass to matcher, if any
|
152
|
-
matcher ? matcher.match(val) : val
|
153
|
-
end
|
154
|
-
end
|
155
|
-
|
156
|
-
end
|
157
|
-
end
|