ranking_day2.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. from random import randint
  2. import sys
  3. import dataset
  4. from selenium import webdriver
  5. import traceback
  6. import datetime
  7. import codecs
  8. import time
  9. import urllib
  10. import argparse
  11. import logging
  12. import sys
  13. from logging.handlers import SysLogHandler
  14. import socket
  15. import pandas as pd
  16. import pymysql
  17. pymysql.install_as_MySQLdb()
  18. import random
  19. from selenium.webdriver.chrome.service import Service
  20. import os
  21. import fire
  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. for elmt in elmts:
  56. try:
  57. href = elmt.get_attribute('href')
  58. datadict['搜尋詞'].append(term)
  59. datadict['結果標題'].append(elmt.text)
  60. datadict['結果網址'].append(href)
  61. datadict['結果名次'].append(str(cnt))
  62. if domain in href:
  63. print(href)
  64. print(elmt.text)
  65. table.insert(
  66. {'title': elmt.text, 'url': href, 'keyword': term, 'dt': datetime.datetime.now(), 'num': cnt})
  67. cnt += 1
  68. except:
  69. print('href2 exception')
  70. traceback.print_exc()
  71. if len(datadict['結果標題']) <= 0:
  72. print('None')
  73. driver.quit()
  74. sys.exit()
  75. # df['搜尋詞']=datadict['搜尋詞']
  76. # df['結果標題']=datadict['結果標題']
  77. # df['結果網址']=datadict['結果網址']
  78. # df['結果名次']=datadict['結果名次']
  79. #
  80. # df.to_excel('/Users/zooeytsai/'+fname+".xls")
  81. driver.quit()
  82. print('中場休息')
  83. time.sleep(randint(90, 120))
  84. def run_once(q):
  85. global driver
  86. result = []
  87. s = Service('/root/driver/chromedriver')
  88. user_agent = rua()
  89. options = webdriver.ChromeOptions()
  90. options.add_argument('--headless')
  91. options.add_argument('--remote-debugging-port=9222')
  92. options.add_experimental_option("debuggerAddress", f"127.0.0.1:{q[2]}")
  93. options.add_argument("--user-agent=" + user_agent)
  94. options.add_argument("--incognito")
  95. driver = webdriver.Chrome(options=options, service=s)
  96. driver.delete_all_cookies()
  97. driver.set_window_size(1400, 1000)
  98. process_one(q)
  99. time.sleep(3)
  100. driver.quit()
  101. class JParams(object):
  102. def get(self, kw, domain, port):
  103. print(kw)
  104. print(domain)
  105. run_once((kw, domain, port))
  106. if __name__ == '__main__':
  107. fire.Fire(JParams)