html_scraper 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 30d7fe3d96af42943051c576917a33c99baf110a
4
+ data.tar.gz: 7fad6c623faf5770b64dc1516f09dccc917d6bf4
5
+ SHA512:
6
+ metadata.gz: 31ccd41b327e3a9a7580483086ab4278fbc6ef5afb916f94aaf7e2e7297a63139a248c33f9de0cc064cf311d26c3d831065074c0eaa84292bdf7d509d2089deb
7
+ data.tar.gz: 31affec6845ac231e762f7e28edc031703aae021b6495f48935f8395f3daf8ebe1c90db915df072e19e153922a9a0ce03b8dd4cd56d158dd2e715e901e46bc3d
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rubocop.yml ADDED
@@ -0,0 +1,50 @@
1
+ # see https://github.com/bbatsov/rubocop#configuration
2
+ # for info on how to configure rubocop
3
+ # see https://github.com/bbatsov/rubocop/blob/master/config/default.yml
4
+ # for default configuration
5
+
6
+ Documentation:
7
+ Enabled: false
8
+
9
+ Metrics/LineLength:
10
+ Max: 200
11
+ # Enabled: false
12
+
13
+ Metrics/MethodLength:
14
+ Max: 40
15
+ # Enabled: false
16
+
17
+ Metrics/ModuleLength:
18
+ Max: 500
19
+ # Enabled: false
20
+
21
+ Metrics/AbcSize:
22
+ # The ABC size is a calculated magnitude, so this number can be a Fixnum or a Float.
23
+ # http://c2.com/cgi/wiki?AbcMetric
24
+ Max: 50
25
+
26
+ Metrics/CyclomaticComplexity:
27
+ # http://www.rubydoc.info/github/bbatsov/rubocop/Rubocop/Cop/Style/CyclomaticComplexity
28
+ Max: 12
29
+
30
+ Metrics/PerceivedComplexity:
31
+ # http://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Metrics/PerceivedComplexity
32
+ Max: 13
33
+
34
+ Style/RedundantReturn:
35
+ Enabled: false
36
+
37
+ Style/GuardClause:
38
+ Enabled: false
39
+
40
+ Metrics/ClassLength:
41
+ Max: 200
42
+
43
+ Style/RedundantSelf:
44
+ Enabled: false
45
+
46
+ Style/NegatedIf:
47
+ Enabled: false
48
+
49
+ AllCops:
50
+ TargetRubyVersion: 2.3
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.3.0
4
+ before_install: gem install bundler -v 1.11.2
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in html_scraper.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 bduran
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,112 @@
1
+ # HtmlScraper
2
+
3
+ HtmlScraper is a ruby gem that transforms the content from a html web page to a json document following a defined html template
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'html_scraper'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install html_scraper
20
+
21
+ ## Usage
22
+
23
+ ### Simple html parsing
24
+
25
+ Expressions sourrounded by `{{ }}` will be parsed as simple json attributes:
26
+
27
+ ```ruby
28
+ template = '
29
+ <div class="person">
30
+ <h5>{{ surname }}</h5>
31
+ <p>{{ name }}</p>
32
+ </div>
33
+ '
34
+ html = '
35
+ <html>
36
+ <body>
37
+ <div class="person">
38
+ <h5>Eastwood</h5>
39
+ <p>Clint</p>
40
+ </div>
41
+ </body>
42
+ </html>
43
+ '
44
+ json = HtmlScraper::Scraper.new(template: template).parse(html)
45
+ ```
46
+
47
+ The json result:
48
+ ```
49
+ {:surname=>"Eastwood", :name=>"Clint"}
50
+ ```
51
+
52
+ ### Iterative data
53
+
54
+ To parse iterative structures define the attribute `hs-repeat` to the html node containing the iteration:
55
+
56
+ ```ruby
57
+ template = '
58
+ <div id="people-list">
59
+ <div class="person" hs-repeat="people">
60
+ <h5>{{ surname }}</h5>
61
+ <p>{{ name }}</p>
62
+ </div>
63
+ </div>
64
+ '
65
+
66
+ html = '
67
+ <html>
68
+ <body>
69
+ <div id="people-list">
70
+ <div class="person">
71
+ <h5>Eastwood</h5>
72
+ <p>Clint</p>
73
+ </div>
74
+ <div class="person">
75
+ <h5>Woods</h5>
76
+ <p>James</p>
77
+ </div>
78
+ <div class="person">
79
+ <h5>Kinski</h5>
80
+ <p>Klaus</p>
81
+ </div>
82
+ </div>
83
+ </body>
84
+ </html>
85
+ '
86
+ json = HtmlScraper::Scraper.new(template: template).parse(html)
87
+ ```
88
+
89
+ The json result:
90
+
91
+ ````ruby
92
+ {:people=>
93
+ [{:surname=>"Eastwood", :name=>"Clint"},
94
+ {:surname=>"Woods", :name=>"James"},
95
+ {:surname=>"Kinski", :name=>"Klaus"}]}
96
+ ```
97
+
98
+ ## Development
99
+
100
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
101
+
102
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
103
+
104
+ ## Contributing
105
+
106
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/html_scraper.
107
+
108
+
109
+ ## License
110
+
111
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
112
+
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rake/testtask'
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << 'test'
6
+ t.libs << 'lib'
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "html_scraper"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'html_scraper/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'html_scraper'
8
+ spec.version = HtmlScraper::VERSION
9
+ spec.authors = ['Bernat Duran']
10
+
11
+ spec.summary = 'Parses the data contained in a html web page to json using a user-defined'
12
+ spec.homepage = 'https://github.com/bduran82/html_scraper.git'
13
+ spec.license = 'MIT'
14
+
15
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
16
+ spec.bindir = 'exe'
17
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
18
+ spec.require_paths = ['lib']
19
+
20
+ spec.add_dependency 'nokogiri', '~> 1.6'
21
+ spec.add_dependency 'activesupport', '~> 4'
22
+
23
+ spec.add_development_dependency 'bundler', '~> 1.11'
24
+ spec.add_development_dependency 'rake', '~> 10.0'
25
+ spec.add_development_dependency 'minitest', '~> 5.0'
26
+ spec.add_development_dependency 'pry'
27
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+ module HtmlScraper
3
+ class Expression
4
+ CODE_PLACEHOLDER = '$'
5
+
6
+ def initialize(text)
7
+ @text = text
8
+ end
9
+
10
+ def evaluate(text)
11
+ result = {}
12
+ if !variable_name.blank?
13
+ result[variable_name.to_sym] = remove_newlines(evaluate_assignation(regexp_filter(text)))
14
+ end
15
+ return result
16
+ end
17
+
18
+ def regexp_filter(text)
19
+ result = text
20
+ if !regexp.blank?
21
+ regexp_match = text.match(regexp)
22
+ if !regexp_match.blank?
23
+ result = regexp_match[0]
24
+ else
25
+ result = ''
26
+ end
27
+ end
28
+ return result
29
+ end
30
+ private :regexp_filter
31
+
32
+ def evaluate_assignation(text)
33
+ value = text
34
+ eval(code.gsub(CODE_PLACEHOLDER, 'value'))
35
+ rescue
36
+ ''
37
+ end
38
+ private :evaluate_assignation
39
+
40
+ def remove_newlines(text)
41
+ return text.split(/[\n\t]/).map(&:strip).join(' ')
42
+ end
43
+ private :remove_newlines
44
+
45
+ def variable_name
46
+ return @variable_name ||= begin
47
+ match_capture(1)
48
+ end
49
+ end
50
+ private :variable_name
51
+
52
+ def regexp
53
+ return @regexp ||= begin
54
+ regexp_match = match_capture(2)
55
+ regexp_match[1..-2] unless regexp_match.blank?
56
+ end
57
+ end
58
+ private :regexp
59
+
60
+ def code
61
+ return @code ||= begin
62
+ code_match = match_capture(3)
63
+ if !code_match.blank?
64
+ code_match[1..-1]
65
+ else
66
+ CODE_PLACEHOLDER
67
+ end
68
+ end
69
+ end
70
+ private :code
71
+
72
+ def match_capture(index)
73
+ return match[index] unless match.blank?
74
+ return nil
75
+ end
76
+ private :match_capture
77
+
78
+ def match
79
+ return @match ||= begin
80
+ @text.match(%r{^\s*(\w+)(/.*/)?\s*(=.*)?\s*$})
81
+ end
82
+ end
83
+ private :match
84
+ end
85
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+ require 'nokogiri'
3
+
4
+ module HtmlScraper
5
+ class Scraper
6
+ def initialize(template:, verbose: false)
7
+ @template = template
8
+ @depth = 0
9
+ @verbose = verbose
10
+ end
11
+
12
+ def parse(html)
13
+ html_template = Nokogiri::HTML(@template)
14
+ return {} if html_template.root.nil?
15
+ template_root = html_template.root.children.first
16
+ html_root = Nokogiri::HTML(html).root
17
+ return inspect(template_root, html_root)
18
+ end
19
+
20
+ def inspect(template_node, html_node)
21
+ result = {}
22
+ tnode_xpath = build_xpath(template_node)
23
+ matching_nodes = html_node.xpath(tnode_xpath)
24
+ log("START #{tnode_xpath}...")
25
+ @depth += 1
26
+ sub_results = matching_nodes.map { |node| parse_node(template_node, node) }
27
+ @depth -= 1
28
+ log("END #{tnode_xpath}: #{sub_results.size} matches")
29
+
30
+ if !template_node.attribute('hs-repeat').blank?
31
+ result[template_node.attribute('hs-repeat').value.to_sym] = sub_results
32
+ else
33
+ result.merge!(sub_results.reduce({}, &:merge))
34
+ end
35
+ return result
36
+ end
37
+
38
+ def parse_node(template_node, html_node)
39
+ expression = template_node.xpath('./text()').text
40
+ result = evaluate_expressions(expression, html_node.text)
41
+ children_results = template_node.children.map { |t_node| inspect(t_node, html_node) }
42
+ return result.merge(children_results.reduce(&:merge))
43
+ end
44
+ private :parse_node
45
+
46
+ def evaluate_expressions(expression, text)
47
+ result = expression.scan(/^\s*{{(.*)}}\s*$/).flatten.reduce({}) do |res, expr|
48
+ res.merge(Expression.new(expr).evaluate(text))
49
+ end
50
+
51
+ return result
52
+ end
53
+ private :evaluate_expressions
54
+
55
+ def build_xpath(template_node)
56
+ xpath = ".//#{template_node.name}"
57
+ attributes = template_node.attributes.reject { |k, _| k.start_with?('hs-') }
58
+ if !attributes.blank?
59
+ selector = attributes.map { |k, v| attribute_selector(k, v) }.join
60
+ xpath = "#{xpath}#{selector}"
61
+ end
62
+ return xpath
63
+ end
64
+ private :build_xpath
65
+
66
+ def attribute_selector(key, value)
67
+ selector = if key == 'class'
68
+ "contains(@#{key}, '#{value}')"
69
+ else
70
+ "@#{key}='#{value}'"
71
+ end
72
+ return "[#{selector}]"
73
+ end
74
+ private :attribute_selector
75
+
76
+ def log(text)
77
+ puts "#{' ' * @depth}#{text}" if @verbose
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,3 @@
1
+ module HtmlScraper
2
+ VERSION = '0.1.0'.freeze
3
+ end
@@ -0,0 +1,7 @@
1
+ require 'active_support/core_ext/string'
2
+ require 'html_scraper/version'
3
+ require 'html_scraper/expression'
4
+ require 'html_scraper/scraper'
5
+
6
+ module HtmlScraper
7
+ end
metadata ADDED
@@ -0,0 +1,141 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: html_scraper
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Bernat Duran
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-08-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: nokogiri
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.6'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.6'
27
+ - !ruby/object:Gem::Dependency
28
+ name: activesupport
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '4'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '4'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.11'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.11'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: minitest
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '5.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '5.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: pry
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ description:
98
+ email:
99
+ executables: []
100
+ extensions: []
101
+ extra_rdoc_files: []
102
+ files:
103
+ - ".gitignore"
104
+ - ".rubocop.yml"
105
+ - ".travis.yml"
106
+ - Gemfile
107
+ - LICENSE.txt
108
+ - README.md
109
+ - Rakefile
110
+ - bin/console
111
+ - bin/setup
112
+ - html_scraper.gemspec
113
+ - lib/html_scraper.rb
114
+ - lib/html_scraper/expression.rb
115
+ - lib/html_scraper/scraper.rb
116
+ - lib/html_scraper/version.rb
117
+ homepage: https://github.com/bduran82/html_scraper.git
118
+ licenses:
119
+ - MIT
120
+ metadata: {}
121
+ post_install_message:
122
+ rdoc_options: []
123
+ require_paths:
124
+ - lib
125
+ required_ruby_version: !ruby/object:Gem::Requirement
126
+ requirements:
127
+ - - ">="
128
+ - !ruby/object:Gem::Version
129
+ version: '0'
130
+ required_rubygems_version: !ruby/object:Gem::Requirement
131
+ requirements:
132
+ - - ">="
133
+ - !ruby/object:Gem::Version
134
+ version: '0'
135
+ requirements: []
136
+ rubyforge_project:
137
+ rubygems_version: 2.5.1
138
+ signing_key:
139
+ specification_version: 4
140
+ summary: Parses the data contained in a html web page to json using a user-defined
141
+ test_files: []