-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract_examples.rb
97 lines (90 loc) · 2.32 KB
/
extract_examples.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
require 'nokogiri'
require 'uri'
require 'net/https'
class Scrape
EXCLUDE_IDS = %w[
about
accessibility
events
how-it-works
javascript-behavior
options
methods
notation
triggers
usage
validation
via-javascript
via-data-attributes
]
def initialize(file)
@urls = []
if File.exist?(file)
IO.read(file).split(/[\r\n]+/).each do |link|
@urls << link
end
else
raise "Import failed: #{file} is missing."
end
end
def get(url)
puts "Downloading: #{url}"
uri = URI(url)
response = nil
begin
Net::HTTP.start(uri.host, uri.port,
use_ssl: uri.scheme == 'https',
verify_mode: OpenSSL::SSL::VERIFY_PEER) do |http|
response = http.request(Net::HTTP::Get.new(uri))
end
rescue
raise "Error: #{uri}"
end
if response.class == Net::HTTPOK
file_name = nil
nodes = []
doc = Nokogiri::HTML(response.body)
doc.css('main').each do |main|
main.children.each do |child|
child_name = child.name
if child_name == 'h1'
file_name = child.text.downcase
child['id'] = nil
nodes << child
elsif child_name == 'h2' && !EXCLUDE_IDS.any? { |e| e == child['id'] }
nodes << child
elsif child_name == 'h3' && !EXCLUDE_IDS.any? { |e| e == child['id'] }
nodes << child
elsif child['class'] == 'bd-example'
nodes << child
elsif !child['class'].nil? && child['class'].include?('bd-example-row')
child.children.each do |sub_child|
if sub_child['class'] == 'bd-example'
nodes << child
end
end
elsif !child['class'].nil? && child['class'].include?('bd-example-border-utils')
child.children.each do |sub_child|
if sub_child['class'] == 'bd-example'
nodes << child
end
end
end
end
end
File.open(File.join(Dir.pwd, 'templates', "#{file_name}.html"), 'w') do |file|
nodes.each do |node|
file.puts(node.to_html)
end
end
end
end
def run
@urls.each do |url|
get(url)
sleep(1) # Be friendly.
end
end
end
s = Scrape.new('bootstrap_docs.txt')
s.run