-
Notifications
You must be signed in to change notification settings - Fork 0
/
adwords.rb
executable file
·82 lines (70 loc) · 2.05 KB
/
adwords.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
#!/usr/bin/env ruby
# coding: utf-8
require 'adwords_api'
require 'mysql2-cs-bind'
require 'yaml'
require 'erb'
require 'hashie'
class Ad
def initialize
config_file = File.expand_path "./database.yml", File.dirname(__FILE__)
db_config = Hashie::Mash.new(YAML.load(ERB.new(IO.read(config_file)).result))
Mysql2::Client.default_query_options.merge!(:symbolize_keys => true)
@client = Mysql2::Client.new(db_config)
end
def get_keyword_ideas(keyword_text)
page_size = 1
api_version = :v201509
adwords = AdwordsApi::Api.new
targeting_idea_srv = adwords.service(:TargetingIdeaService, api_version)
selector = {
:idea_type => 'KEYWORD',
:request_type => 'STATS',
:requested_attribute_types =>
['KEYWORD_TEXT','TARGETED_MONTHLY_SEARCHES'],
:search_parameters => [
{
:xsi_type => 'RelatedToQuerySearchParameter',
:queries => [keyword_text]
},
{
:xsi_type => 'LanguageSearchParameter',
:languages => [{:id => 1005}]
}
],
:paging => {
:start_index => 0,
:number_results => page_size
}
}
offset = 0
results = []
begin
page = targeting_idea_srv.get(selector)
results += page[:entries] if page and page[:entries]
offset += page_size
selector[:paging][:start_index] = offset
end while offset < page_size
results.each do |result|
data = result[:data]
@result = []
@result << [
keyword: data['KEYWORD_TEXT'][:value],
data: data['TARGETED_MONTHLY_SEARCHES'][:value]
]
end
return @result
end
def insert_data(array)
keyword = array[0][0][:keyword]
array[0][0][:data].each do |d|
@client.xquery("insert into adwords (keyword,year,month,count) values (?,?,?,?) on duplicate key update count = ?", keyword, d[:year].to_i, d[:month].to_i, d[:count].to_i, d[:count].to_i)
end
end
end
keyword_text = ARGV
keyword_text.each do |word|
ad = Ad.new
res = ad.get_keyword_ideas(word)
ad.insert_data(res)
end