-
Notifications
You must be signed in to change notification settings - Fork 7
/
baidu.py
44 lines (38 loc) · 1.68 KB
/
baidu.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
import json
import time
import datetime
import urllib.parse
import urllib.request
base_url = "https://api.baidu.com/json/tongji/v1/ReportService/getData"
class Baidu(object):
def __init__(self, siteId, username, password, token):
self.siteId = siteId
self.username = username
self.password = password
self.token = token
def getresult(self, start_date, end_date, method, metrics, **kw):
base_url = "https://api.baidu.com/json/tongji/v1/ReportService/getData"
body = {"header": {"account_type": 1, "password": self.password, "token": self.token,
"username": self.username},
"body": {"siteId": self.siteId, "method": method, "start_date": start_date,
"end_date": end_date, "metrics": metrics}}
for key in kw:
body['body'][key] = kw[key]
data = bytes(json.dumps(body), 'utf8')
req = urllib.request.Request(base_url, data)
response = urllib.request.urlopen(req)
the_page = response.read()
return the_page.decode("utf-8")
if __name__ == '__main__':
# 日期开始
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
fifteenago = today - datetime.timedelta(days=7)
end, start = str(yesterday).replace("-", ""), str(fifteenago).replace("-", "")
# 日期结束
bd = Baidu(yoursiteid, "your username", "your password", "your token")
result = bd.getresult(start, end, "overview/getTimeTrendRpt",
"pv_count,visitor_count,ip_count,bounce_ratio,avg_visit_time")
result = json.loads(result)
base = result["body"]["data"][0]["result"]["items"]
print(base)