ranking_world_2.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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(executable_path=r'C:\Users\Administrator\Downloads\chromedriver_107\chromedriver', options=options)
  66. except:
  67. traceback.print_exc()
  68. return
  69. driver.delete_all_cookies()
  70. driver.set_window_size(950, 20000)
  71. return
  72. except:
  73. traceback.print_exc()
  74. driver = None
  75. return None
  76. def scrolling(driver, pgnum):
  77. ub = driver.find_element("css selector",'body')
  78. for i in range(pgnum):
  79. ub.send_keys(Keys.PAGE_DOWN)
  80. if pgnum > 1:
  81. time.sleep(0.3)
  82. def run_once(jsobj):
  83. table = db['nda_log']
  84. print(jsobj)
  85. global driver
  86. if driver is None:
  87. time.sleep(8)
  88. re_get_webdriver()
  89. if driver is None:
  90. return
  91. try:
  92. kw = jsobj['kw']
  93. url = jsobj['url']
  94. # if jsobj.get('domain') is None:
  95. # exclude = jsobj['exclude']
  96. # domain = None
  97. # else:
  98. # domain = jsobj['domain']
  99. # exclude = None
  100. driver.get(url)
  101. time.sleep(6)
  102. scrolling(driver,10)
  103. time.sleep(20)
  104. elmts = driver.find_elements(By.XPATH, "//div[@class='yuRUbf']/a")
  105. numresults = len(elmts)
  106. print('搜尋結果數量', numresults)
  107. time.sleep(20)
  108. # driver.save_screenshot('C:\/Users\/s1301\/Pictures\/Saved Pictures\/angelo koo\/' +date +fname + ".png")
  109. if numresults == 0:
  110. send_msg('stop working...')
  111. sys.exit()
  112. datadict = {'搜尋詞': [], '結果標題': [], '結果網址': [], '結果名次': [], '結果說明': []}
  113. df = pd.DataFrame()
  114. idx = 1
  115. found = False
  116. test_lst = []
  117. txt_dict = {}
  118. for elmt in elmts:
  119. href = elmt.get_attribute('href')
  120. txt = elmt.text
  121. desc = None
  122. if domain in href:
  123. print(href)
  124. print("ranking", idx)
  125. webdriver.ActionChains(driver).move_to_element(elmt).perform()
  126. # elmt.click()
  127. webdriver.ActionChains(driver).move_to_element(elmt).click().perform()
  128. print('clicked....')
  129. table.insert({'ranking': idx, 'kw': kw, 'results': numresults, 'url': href, 'title': txt,
  130. 'dt': datetime.datetime.now(), 'client': 'i5'})
  131. time.sleep(6)
  132. db.close()
  133. break
  134. idx += 1
  135. # if exclude is not None:
  136. # print('exclude')
  137. # elmt = random.choice(test_lst[5:])
  138. # print(elmt)
  139. # print(txt_dict[elmt])
  140. #
  141. # webdriver.ActionChains(driver).move_to_element(elmt).perform()
  142. # # elmt.click()
  143. # webdriver.ActionChains(driver).move_to_element(elmt).click().perform()
  144. # time.sleep(5)
  145. #
  146. # if not found:
  147. # table.insert(
  148. # {'ranking': -1, 'kw': kw, 'results': numresults, 'url': '', 'title': '未收錄', 'descrption': desc})
  149. # df.to_excel('C:\/Users\/s1301\/Pictures\/Saved Pictures\/angelo koo\/'+date+fname+".xls")
  150. except:
  151. print('exception')
  152. traceback.print_exc()
  153. # time.sleep(9999)
  154. # driver.save_screenshot('c:/tmp/seo/'+kw+".png")
  155. driver.quit()
  156. sys.exit()
  157. city_lst = ["w+CAIQICIWTmV3IFlvcmssVW5pdGVkIFN0YXRlcw&gws_rd=cr",
  158. "w+CAIQICIYV2FzaGluZ3RvbixVbml0ZWQgU3RhdGVz&gws_rd=cr",
  159. "w+CAIQICIbTWlhbWksRmxvcmlkYSxVbml0ZWQgU3RhdGVz&gws_rd=cr",
  160. "w+CAIQICIeQ2hpY2FnbyxJbGxpbm9pcyxVbml0ZWQgU3RhdGVz&gws_rd=cr"]
  161. # cursor=db.query('select json from seo_jobs where cust="美東" and plan="形象SEO" order by rand() limit 1')
  162. # for c in cursor:
  163. # js=json.loads(c['json'])
  164. # prefix=js['prefix']
  165. # postfix=js['postfix']
  166. # domain=js['domain'][0]
  167. # positive=js['positive']
  168. # rnd=js['rnd']
  169. #
  170. # kw1=random.choice(positive)
  171. # kw2=random.choice(rnd)
  172. # kw=prefix+" "+kw1+" "+kw2
  173. # city = random.choice(city_lst)
  174. url = "https://www.google.com/search?q=angelo+koo&hl=en&gl=us&num=100&uule=w+CAIQICIWTmV3IFlvcmssVW5pdGVkIFN0YXRlcw&gws_rd=cr"
  175. run_once({'kw':'angelo koo','url':url})