Skip to content

Instantly share code, notes, and snippets.

@zackster
Created February 7, 2017 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zackster/6c90572115b189499ea9ae0545113a34 to your computer and use it in GitHub Desktop.
Save zackster/6c90572115b189499ea9ae0545113a34 to your computer and use it in GitHub Desktop.
Automatically export your reddit ads data to a csv file so you can review CTR, CPC, subreddits targeted, etc.
require 'parallel'
require 'httparty'
require 'pry'
def fetch_reddit_page(reddit_link)
cookies = [ ] # get these from EditThisCookie chrome extension: Export -> Copy to clipboard (copies as a ruby-friendly array of hashes)
c = {}
cookies.map{ |x|
c[x[:name]] = x[:value]
}
ads_page = HTTParty.get reddit_link, {
cookies: c,
'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17"
}
end
require 'nokogiri'
results = []
ads_page = fetch_reddit_page 'https://www.reddit.com/promoted/'
nok = Nokogiri(ads_page.response.body)
ads = nok.css('li > a').select{|x| x.text == 'traffic' }.map{|x|x.attributes['href'].value}
while (nok.css('.next-button > a').size > 0) do
next_page_link = nok.css('.next-button > a').first.attributes['href'].value
next_page = fetch_reddit_page(next_page_link)
nok = Nokogiri(next_page.response.body)
nok.css('li > a').select{|x| x.text == 'traffic' }.each{ |x|
ads << x.attributes['href'].value
}
end
results = Parallel.map(ads) do |details_page|
begin
puts "fetching #{details_page}"
ads_page = fetch_reddit_page details_page
nok = Nokogiri(ads_page.response.body)
# Ad Copy, Subreddits Targeted, Clicks, CPC, CTR
ad_copy = nok.css('p.title > a.title').text
subreddits_targeted = nok.css('.traffic-table.promocampaign-table > tr')[0..-2].map{|tr| tr.css('td')[5].text }.uniq
clicks = nok.css('.traffic-table.promocampaign-table > tr')[-1].css('td')[12].text
cpc = nok.css('.traffic-table.promocampaign-table > tr')[-1].css('td')[14].text
ctr = nok.css('.traffic-table.promocampaign-table > tr')[-1].css('td')[13].text
[details_page, ad_copy, subreddits_targeted, clicks, cpc, ctr]
rescue
nil
end
end
puts results
require 'csv'
results = results.reject(&:nil?)
File.open("reddit_campaigns.csv", "w") {|f| f.write(results.inject([]) { |csv, row| csv << CSV.generate_line(row) }.join(""))}
@zackster
Copy link
Author

zackster commented Feb 7, 2017

If you found value in this, please check out my freelance programming jobs board

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment