ranking_day.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. import sys
  2. import dataset
  3. from selenium import webdriver
  4. import traceback
  5. import datetime
  6. import codecs
  7. import time
  8. import urllib
  9. import argparse
  10. import logging
  11. import sys
  12. from logging.handlers import SysLogHandler
  13. import socket
  14. import pandas as pd
  15. import random
  16. from selenium.webdriver.common.by import By
  17. from selenium.webdriver.chrome.service import Service
  18. import os
  19. from random import randint
  20. import pymysql
  21. pymysql.install_as_MySQLdb()
  22. path = 'C:\portable\chromedriver'
  23. path_z = '/Users/zooeytsai/Downloads/chromedriver 2'
  24. driver = None
  25. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/seo?charset=utf8mb4')
  26. lst = []
  27. table = db['google_rank']
  28. def rua():
  29. pool = [
  30. "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0",
  31. "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0",
  32. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
  33. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36",
  34. "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
  35. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36",
  36. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36 OPR/68.0.3618.125",
  37. ]
  38. return random.choice(pool)
  39. def process_one(item):
  40. global driver
  41. term = item[0]
  42. domain = item[1]
  43. print(term, domain)
  44. escaped_search_term = urllib.parse.quote(term)
  45. googleurl = 'https://www.google.com/search?q={}&num={}&hl={}'.format(escaped_search_term, 100, 'zh-TW')
  46. print(googleurl)
  47. driver.get(googleurl)
  48. time.sleep(6)
  49. # fname=term.replace(' ','_')
  50. # driver.save_screenshot('c:/tmp/seo/'+fname+'.png')
  51. # df=pd.DataFrame()
  52. elmts = driver.find_elements(By.XPATH,"//div[@class='yuRUbf']/a")
  53. cnt = 1
  54. datadict = {'搜尋詞': [], '結果標題': [], '結果網址': [], '結果名次': []}
  55. if len(elmts) == 0:
  56. print('chrome異常')
  57. os.chdir('/root')
  58. os.system('python3 reboot.py')
  59. for elmt in elmts:
  60. try:
  61. href = elmt.get_attribute('href')
  62. datadict['搜尋詞'].append(term)
  63. datadict['結果標題'].append(elmt.text)
  64. datadict['結果網址'].append(href)
  65. datadict['結果名次'].append(str(cnt))
  66. if domain in href:
  67. print(href)
  68. print(elmt.text)
  69. table.insert(
  70. {'title': elmt.text, 'url': href, 'keyword': term, 'dt': datetime.datetime.now(), 'num': cnt})
  71. cnt += 1
  72. except:
  73. print('href2 exception')
  74. traceback.print_exc()
  75. if len(datadict['結果標題']) <= 0:
  76. print('None')
  77. driver.quit()
  78. sys.exit()
  79. # df['搜尋詞']=datadict['搜尋詞']
  80. # df['結果標題']=datadict['結果標題']
  81. # df['結果網址']=datadict['結果網址']
  82. # df['結果名次']=datadict['結果名次']
  83. #
  84. # df.to_excel('/Users/zooeytsai/'+fname+".xls")
  85. driver.quit()
  86. print('中場休息')
  87. time.sleep(randint(90, 120))
  88. def run_once(pport, item):
  89. global driver
  90. result = []
  91. s = Service('/root/driver/chromedriver')
  92. user_agent = rua()
  93. options = webdriver.ChromeOptions()
  94. options.add_argument('--headless')
  95. options.add_argument('--remote-debugging-port=9222')
  96. options.add_experimental_option("debuggerAddress", f"127.0.0.1:{pport}")
  97. options.add_argument("--user-agent=" + user_agent)
  98. options.add_argument("--incognito")
  99. driver = webdriver.Chrome(options=options, service=s)
  100. driver.delete_all_cookies()
  101. driver.set_window_size(1400, 1000)
  102. process_one(item)
  103. time.sleep(3)
  104. driver.quit()
  105. cursor = db.query('select term,domain from seo.selected_kw')
  106. for c in cursor:
  107. lst.append([c['term'], c['domain']])
  108. for i in lst:
  109. print('這裡', i)
  110. while True:
  111. try:
  112. os.system('docker container restart tiny9')
  113. time.sleep(1)
  114. run_once(9928, i)
  115. print('docker開啟完成')
  116. cur = db.query('select * from seo.google_rank order by id desc limit 1')
  117. for c in cur:
  118. kw = c['keyword']
  119. if kw != i[0]:
  120. print('稍等,上一筆待完成')
  121. time.sleep(60)
  122. break
  123. except:
  124. os.system('docker container restart tiny9')
  125. time.sleep(15)
  126. print('等待進行下一個關鍵字')
  127. time.sleep(5)