ranking_world.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. # import redis
  2. import time
  3. import traceback
  4. # import json
  5. from selenium import webdriver
  6. from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
  7. import time
  8. import os
  9. from selenium.webdriver.support.ui import WebDriverWait
  10. from selenium.webdriver.common.by import By
  11. from selenium.webdriver.support import expected_conditions as EC
  12. import dataset
  13. from selenium.webdriver.common.keys import Keys
  14. import json
  15. import random
  16. import time
  17. import redis
  18. import sys
  19. import codecs
  20. import pandas as pd
  21. import random
  22. import os
  23. import time
  24. import datetime
  25. from selenium.webdriver.chrome.service import Service
  26. import dataset
  27. import pymysql
  28. pymysql.install_as_MySQLdb()
  29. from userAgentRandomizer import userAgents
  30. import requests
  31. driver = None
  32. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/seo?charset=utf8mb4')
  33. headers = {
  34. "Authorization": "Bearer " + "6SDULL1Ebklduc6TFxa97AFto5Sj21kyJ30CxiLiSoi",
  35. "Content-Type": "application/x-www-form-urlencoded"
  36. }
  37. def send_msg(kw):
  38. params = {"message": kw}
  39. r = requests.post("https://notify-api.line.me/api/notify", headers=headers, params=params)
  40. def re_get_webdriver():
  41. global port
  42. global driver
  43. result = []
  44. if driver is not None:
  45. print('closing....')
  46. driver.quit()
  47. os.system('killall chrome')
  48. print('quit....')
  49. driver = None
  50. try:
  51. ua = userAgents()
  52. user_agent = ua.random()
  53. options = webdriver.ChromeOptions()
  54. options.add_argument("--no-sandbox")
  55. options.add_argument("--disable-dev-shm-usage")
  56. options.add_argument("--headless")
  57. print(user_agent)
  58. options.add_experimental_option('prefs', {'intl.accept_languages': 'en,en_US'})
  59. options.add_argument("--incognito")
  60. driver = None
  61. try:
  62. if os.name == 'nt':
  63. driver = webdriver.Chrome(options=options)
  64. else:
  65. driver = webdriver.Chrome(
  66. executable_path=r'C:\Users\Administrator\Downloads\chromedriver_108\chromedriver', options=options)
  67. except:
  68. traceback.print_exc()
  69. return
  70. driver.delete_all_cookies()
  71. driver.set_window_size(950, 20000)
  72. return
  73. except:
  74. traceback.print_exc()
  75. driver = None
  76. return None
  77. def scrolling(driver, pgnum):
  78. ub = driver.find_element_by_css_selector('body')
  79. for i in range(pgnum):
  80. ub.send_keys(Keys.PAGE_DOWN)
  81. if pgnum > 1:
  82. time.sleep(0.3)
  83. def run_once(jsobj):
  84. table = db['google_rank']
  85. print(jsobj)
  86. global driver
  87. i = 100
  88. if driver is None:
  89. time.sleep(8)
  90. re_get_webdriver()
  91. if driver is None:
  92. return
  93. try:
  94. kw = jsobj['kw']
  95. fname = jsobj['fname']
  96. if jsobj.get('domain') is None:
  97. exclude = jsobj['exclude']
  98. domain = None
  99. else:
  100. domain = jsobj['domain']
  101. exclude = None
  102. city_map = {'chicago': ['42.04866173771369', '-87.68260072643513'],
  103. 'miami': ['25.764458843530548', '-80.19787522585152'],
  104. 'wc': ['38.96071674051165', '-77.03155367248387'],
  105. 'ny': ['40.76774141099703', '-73.98439238945637']}
  106. city = jsobj['fname']
  107. print(city)
  108. Map_coordinates = dict({
  109. "latitude": float(city_map[f"{city}"][0]),
  110. "longitude": float(city_map[f"{city}"][1]),
  111. "accuracy": 100
  112. })
  113. # 芝加哥、邁阿密、紐約、華盛頓
  114. driver.execute_cdp_cmd("Emulation.setGeolocationOverride", Map_coordinates)
  115. driver.get('https://www.google.com?num=100&lr=lang_en')
  116. time.sleep(3)
  117. print(driver.current_url)
  118. elmt = driver.find_element(By.XPATH, "//input[@name='q']")
  119. time.sleep(1)
  120. elmt.send_keys(kw)
  121. elmt.send_keys(Keys.ENTER)
  122. time.sleep(6)
  123. elmts = driver.find_elements(By.XPATH, "//div[@class='yuRUbf']/a")
  124. numresults = len(elmts)
  125. print('搜尋結果數量', numresults)
  126. # driver.save_screenshot('C:\/Users\/s1301\/Pictures\/Saved Pictures\/' + fname + ".png")
  127. if numresults == 0:
  128. send_msg('stop working...')
  129. sys.exit()
  130. datadict = {'搜尋詞': [], '結果標題': [], '結果網址': [], '結果名次': [], '結果說明': []}
  131. df = pd.DataFrame()
  132. idx = 1
  133. found = False
  134. test_lst = []
  135. txt_dict = {}
  136. for elmt in elmts:
  137. href = elmt.get_attribute('href')
  138. txt = elmt.text
  139. desc = None
  140. try:
  141. elmt2 = elmt.find_element(By.XPATH, "./../../..//div[@data-content-feature=1]")
  142. desc = elmt2.text
  143. except:
  144. desc = None
  145. # print(desc)
  146. table.insert(
  147. {'title': elmt.text, 'url': href, 'keyword': kw, 'dt': datetime.datetime.now(), 'ranking': idx})
  148. datadict['搜尋詞'].append(kw)
  149. datadict['結果標題'].append(txt)
  150. datadict['結果網址'].append(href)
  151. datadict['結果名次'].append(str(idx))
  152. datadict['結果說明'].append(desc)
  153. if len(txt) > 10:
  154. if domain is not None:
  155. for d in domain:
  156. if d in href:
  157. print('found....')
  158. print('clicked....')
  159. print(href)
  160. print(txt)
  161. print("ranking", idx)
  162. found = True
  163. return
  164. else:
  165. ex = False
  166. for ee in exclude:
  167. if ee in href:
  168. ex = True
  169. if not ex:
  170. test_lst.append(elmt)
  171. txt_dict[elmt] = txt
  172. idx += 1
  173. if exclude is not None:
  174. print('exclude')
  175. elmt = random.choice(test_lst[5:])
  176. print(elmt)
  177. print(txt_dict[elmt])
  178. webdriver.ActionChains(driver).move_to_element(elmt).perform()
  179. # elmt.click()
  180. webdriver.ActionChains(driver).move_to_element(elmt).click().perform()
  181. time.sleep(5)
  182. if not found:
  183. table.insert(
  184. {'ranking': -1, 'kw': kw, 'results': numresults, 'url': '', 'title': '未收錄', 'descrption': desc})
  185. df['搜尋詞'] = datadict['搜尋詞']
  186. df['結果標題'] = datadict['結果標題']
  187. df['結果網址'] = datadict['結果網址']
  188. df['結果名次'] = datadict['結果名次']
  189. df['結果說明'] = datadict['結果說明']
  190. # df.to_excel('C:\/Users\/s1301\/Pictures\/Saved Pictures\/'+fname+".xls")
  191. except:
  192. print('exception')
  193. traceback.print_exc()
  194. # time.sleep(9999)
  195. # driver.save_screenshot('c:/tmp/seo/'+kw+".png")
  196. driver.quit()
  197. sys.exit()
  198. class JParams(object):
  199. def get(self, jsobj):
  200. run_once(jsobj)
  201. if __name__ == '__main__':
  202. fire.Fire(JParams)