-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsearch-console-api.py
166 lines (146 loc) · 5.26 KB
/
search-console-api.py
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import os
import httplib2
import json
import argparse
import datetime
import csv
import calendar
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client import tools
from apiclient.discovery import build
from apiclient import errors
class gscApi:
api = None
site = ''
def __init__(self,site):
self.oathInit()
self.site = site
def oathInit(self):
parser = argparse.ArgumentParser(parents=[tools.argparser])
flags = parser.parse_args()
flow = flow_from_clientsecrets('secret.json', scope='https://www.googleapis.com/auth/webmasters.readonly', redirect_uri='http://localhost:8080/oauth2callback')
flow.params['access_type'] = 'offline'
flow.params['approval_prompt'] = 'force'
storage = Storage('.' + os.path.basename(__file__))
credentials = storage.get()
if credentials is not None and credentials.access_token_expired:
try:
credentials.refresh(h)
except:
pass
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(httplib2.Http())
self.api = build('webmasters','v3', http=http)
def reauth(self):
parser = argparse.ArgumentParser(parents=[tools.argparser])
flags = parser.parse_args()
flow = flow_from_clientsecrets('gmbsecret.json', scope='https://www.googleapis.com/auth/webmasters.readonly', redirect_uri='http://localhost:8080/oauth2callback')
flow.params['access_type'] = 'offline'
flow.params['approval_prompt'] = 'force'
storage = Storage('.' + os.path.basename(__file__))
credentials = storage.get()
credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(httplib2.Http())
self.api = build('webmasters','v3', http=http)
def initService(self):
jsonLocation = 'credentials.json'
scope = ['https://www.googleapis.com/auth/cloud-platform','email','https://www.googleapis.com/auth/webmasters.readonly',
'https://www.googleapis.com/auth/userinfo.email'
]
credentials = service_account.Credentials.from_service_account_file(jsonLocation,scopes=scope,subject='[email protected]')
scoped_credentials = credentials.with_scopes(['email'])
delegated_credentials = credentials.with_subject('[email protected]')
service = discovery.build('webmasters','v3',credentials = delegated_credentials)
print(service)
siteList = service.sites().list().execute()
print(siteList)
def query(self,startDate,endDate,dimensions = [],limit = 25000,start = 0,filters = []):
request = {
'startDate':startDate,
'endDate':endDate,
'dimensions':dimensions,
'rowLimit':limit,
'startRow':start
}
if filters != []:
request['dimensionFilterGroups'] = [{'filters':filters}]
return self.api.searchanalytics().query(siteUrl=self.site,body=request).execute()
def dailyKeywordsByPage(site,startDate,endDate,csvName):
g = gscApi(site)
g.reauth()
thisPage = 0
maxPages = 100
kwData = []
while thisPage < maxPages:
batch = g.query(startDate,endDate,['date','page','query'],25000,(thisPage * 25000))
#print(batch['rows'])
kwData.extend(batch['rows'])
if len(batch['rows']) != 25000:
break
thisPage = thisPage + 1
print(thisPage)
print(len(kwData))
with open(csvName + ' - GSC Daily.csv', 'w', newline = '',encoding='utf8') as csvfile:
output = csv.writer(csvfile, delimiter=',', quotechar='"')
csvHeader = ['Date','Page','Query','Clicks','Impressions','CTR','Position']
output.writerow(csvHeader)
for thisResult in kwData:
thisRow = thisResult['keys']
thisRow.append(thisResult['clicks'])
thisRow.append(thisResult['impressions'])
thisRow.append(thisResult['ctr'])
thisRow.append(thisResult['position'])
output.writerow(thisRow)
def monthlyKeywordsByPage(site,csvName):
g = gscApi(site)
g.reauth()
maxPages = 50
dateRange = [
[2019,1],
[2019,2],
[2019,3],
[2019,4],
[2019,5],
[2019,6],
[2019,7],
[2019,8],
[2019,9],
[2019,10],
[2019,11],
[2019,12]
]
exportData = []
for thisDate in dateRange:
days = calendar.monthrange(thisDate[0],thisDate[1])
sd = datetime.datetime(thisDate[0],thisDate[1],1)
ed = datetime.datetime(thisDate[0],thisDate[1],days[1])
thisPage = 0
kwData = []
while thisPage < maxPages:
batch = g.query(sd.strftime("%Y-%m-%d"),ed.strftime("%Y-%m-%d"),['device','page','query'],25000,(thisPage * 25000))
if 'rows' in batch:
kwData.extend(batch['rows'])
if len(batch['rows']) != 25000:
break
thisPage = thisPage + 1
print(thisDate[0],thisDate[1],thisPage)
else:
break
exportData.append({'date':str(thisDate[0]) + '-' + str(thisDate[1]),'data': kwData})
print('Rows -',len(kwData))
with open(csvName + ' GSC Monthly.csv', 'w', newline = '',encoding='utf8') as csvfile:
output = csv.writer(csvfile, delimiter=',', quotechar='"')
csvHeader = ['Date','Device','Page','Query','Clicks','Impressions','CTR','Position']
output.writerow(csvHeader)
for thisData in exportData:
for thisResult in thisData['data']:
thisRow = [thisData['date']]
thisRow.extend(thisResult['keys'])
thisRow.append(thisResult['clicks'])
thisRow.append(thisResult['impressions'])
thisRow.append(thisResult['ctr'])
thisRow.append(thisResult['position'])
output.writerow(thisRow)
monthlyKeywordsByPage('https://www.example.com','Example.com GSC Data')