gsc_dump.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import traceback
  2. import copy
  3. import operator
  4. import codecs
  5. import sys
  6. import os
  7. import searchconsole
  8. import dataset
  9. import datetime
  10. import time
  11. fname=os.path.abspath(__file__)
  12. elmts=fname.split(os.path.sep)
  13. path2=os.path.sep.join(elmts[0:-1])
  14. keysdir=path2+os.path.sep+'keys'+os.path.sep
  15. account = searchconsole.authenticate(client_config=keysdir+'client_secret.json',credentials=keysdir+'credentials.json')
  16. webproperty = account['https://hhh.com.tw/']
  17. #db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  18. db = dataset.connect('mysql://choozmo:pAssw0rd@127.0.0.1:3306/hhh?charset=utf8mb4')
  19. table=db['gsc_weekly']
  20. #report=webproperty.query.range('2021-01-01', '2020-01-02').dimension('page','query').get()
  21. report=webproperty.query.range('2021-05-30', '2020-06-05').dimension('query').get()
  22. total_pos=0
  23. total_count=0
  24. total_clicks=0
  25. records=[]
  26. ts = time.time()
  27. sessionid=int(ts)
  28. for r in report:
  29. # print(r)
  30. query=r[0]
  31. clicks=r[1]
  32. impressions=r[2]
  33. ctr=r[3]
  34. position=r[4]
  35. records.append({'sessionid':sessionid,'query':query,'clicks':int(clicks),'impressions':int(impressions),'ctr':float(ctr),'position':float(position),'dt':datetime.datetime.now()})
  36. print('complete')
  37. db.begin()
  38. for r in records:
  39. try:
  40. table.insert(r)
  41. db.commit()
  42. except:
  43. db.rollback()
  44. print('done')