-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscraper.rb
More file actions
64 lines (53 loc) · 1.77 KB
/
Copy pathscraper.rb
File metadata and controls
64 lines (53 loc) · 1.77 KB
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
require 'rubygems'
require 'nokogiri'
require 'open-uri'
require 'json'
require 'csv'
# Base Instagram URL
BASE_URL = "https://instagram.com/"
# List of usernames to scrape
HANDLE_LIST = ["KyleAsaff", "NBA", "football", "espn", "tsn", "sportsillustrated", "HBO"]
# Keywords to use to match in bio
KEY_PHRASES = ["sports", "hbo"]
# Generate new CSV with correct headers
CSV.open("output.csv", "wb") do |csv|
csv << ["Brand Handle", "Website", "Follower Count", "Following Count"]
end
# Scrape each username in array
HANDLE_LIST.each do |handle|
doc = Nokogiri.HTML(open(BASE_URL+handle))
raw = doc.css('script')[5].text
trim = raw.match(/window._sharedData = ((.*));/)[1]
# Parse plain text to JSON
data = JSON.parse(trim)
# Skip if nil
if (data["entry_data"]["ProfilePage"][0]["user"] rescue nil).nil?
puts "<Error> Skipping "+handle
next
end
puts "Checking "+handle+"..."
data = data["entry_data"]["ProfilePage"][0]["user"]
KEY_PHRASES.each do |phrase|
# Format data for non case-sensitive exact phrase matching (ignoring punctuation)
phrase = phrase.downcase.gsub(/[^#a-z0-9\s]/i, '')
phrase = phrase.center(phrase.length+2)
stripped = data["biography"].downcase.gsub(/[^#a-z0-9\s]/i, '')
stripped = stripped.center(stripped.length+2)
# Check if bio includes key phrase
if stripped.include? phrase
user = [{
'username' => data["username"],
'external_url' => data["external_url"],
'followed_by' => data["followed_by"]["count"],
'follows' => data["follows"]["count"],
}]
# Save accounts with a positive match to CSV
CSV.open("output.csv", "ab") do |csv|
user.each do |x|
csv << x.values
end
end
break
end
end
end