gen_seo2.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. #import redis
  2. import time
  3. import traceback
  4. #import json
  5. from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
  6. import time
  7. import os
  8. from selenium.webdriver.support.ui import WebDriverWait
  9. from selenium.webdriver.support import expected_conditions as EC
  10. import dataset
  11. from selenium import webdriver
  12. from selenium.webdriver.common.by import By
  13. from selenium.webdriver.common.keys import Keys
  14. from selenium.webdriver.chrome.service import Service
  15. import json
  16. import random
  17. import time
  18. import datetime
  19. import sys
  20. import codecs
  21. import random
  22. import os
  23. import time
  24. import requests
  25. import pymysql
  26. import urllib.parse
  27. pymysql.install_as_MySQLdb()
  28. from userAgentRandomizer import userAgents
  29. driver=None
  30. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/seo?charset=utf8mb4')
  31. headers = {
  32. "Authorization": "Bearer " + "6SDULL1Ebklduc6TFxa97AFto5Sj21kyJ30CxiLiSoi",
  33. "Content-Type": "application/x-www-form-urlencoded"
  34. }
  35. def send_msg(kw):
  36. params = {"message":kw}
  37. r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
  38. blacklist = ['https://www.chinatimes.com/realtimenews/20220613003142-260402']
  39. def re_get_webdriver():
  40. global port
  41. global driver
  42. result=[]
  43. if driver is not None:
  44. print('closing....')
  45. driver.quit()
  46. os.system('killall chrome')
  47. print('quit....')
  48. driver=None
  49. try:
  50. options = webdriver.ChromeOptions()
  51. # options.add_argument("user-agent=%s" % user_agent)
  52. options.add_argument('--headless')
  53. options.add_argument("--incognito")
  54. driver = webdriver.Chrome(options=options)
  55. driver.delete_all_cookies()
  56. driver.set_window_size(1400,1000)
  57. except:
  58. traceback.print_exc()
  59. driver=None
  60. return None
  61. def getDriver():
  62. ua=userAgents().random()
  63. options = webdriver.ChromeOptions()
  64. #print(ua)
  65. #options.add_argument("user-agent="+ua)
  66. options.add_argument('--headless')
  67. options.add_argument('--incognito')
  68. options.add_argument('--no-sandbox')
  69. driver=webdriver.Chrome(options=options)
  70. driver.set_window_size(1400,1000)
  71. return driver
  72. def run_once(jsobj):
  73. table=db['nda_log']
  74. print(jsobj)
  75. global driver
  76. # i=random.randint(0,9)
  77. i=100
  78. driver=getDriver()
  79. try:
  80. kw=jsobj['kw']
  81. if jsobj.get('domain') is None:
  82. exclude=jsobj['exclude']
  83. domain=None
  84. else:
  85. domain=jsobj['domain']
  86. exclude=None
  87. googleurl = 'https://www.google.com/search?q={}&num={}&hl={}'.format(urllib.parse.quote(kw), 100, 'zh-TW')
  88. driver.get(googleurl)
  89. time.sleep(6)
  90. print(driver.current_url)
  91. if 'sorry' in driver.current_url:
  92. print("URL Error: Caught")
  93. driver.quit()
  94. return
  95. # elmt = driver.find_element(By.XPATH, "//input[@name='q']")
  96. # time.sleep(1)
  97. # elmt.send_keys(kw)
  98. # elmt.send_keys(Keys.ENTER)
  99. # time.sleep(6)
  100. elmts = driver.find_elements(By.XPATH, "//div[@class='yuRUbf']//a")
  101. numresults=len(elmts)
  102. print('搜尋結果數量',numresults)
  103. if numresults==0:
  104. driver.quit()
  105. return
  106. idx=1
  107. found=False
  108. test_lst=[]
  109. txt_dict={}
  110. for elmt in elmts:
  111. href=elmt.get_attribute('href')
  112. txt=elmt.text
  113. if len(txt)>10:
  114. if domain is not None:
  115. if domain in href:
  116. print('found....')
  117. print('clicked....')
  118. print(href)
  119. print("ranking", idx)
  120. found=True
  121. webdriver.ActionChains(driver).move_to_element(elmt).perform()
  122. # elmt.click()
  123. webdriver.ActionChains(driver).move_to_element(elmt).click().perform()
  124. table.insert({'ranking':idx,'kw':kw,'results':numresults,'url':href,'title':txt,'dt':datetime.datetime.now(),'client':jsobj['cust']})
  125. time.sleep(5)
  126. page_height = driver.execute_script("return document.body.scrollHeight")
  127. scroll_step = page_height // 4
  128. current_height = 0
  129. while current_height < page_height:
  130. driver.execute_script(f"window.scrollTo(0, {current_height + scroll_step});")
  131. time.sleep(3)
  132. current_height += scroll_step
  133. time.sleep(10)
  134. break
  135. else:
  136. ex=False
  137. for ee in exclude:
  138. if ee in href:
  139. ex=True
  140. if not ex:
  141. test_lst.append(elmt)
  142. txt_dict[elmt]=txt
  143. idx+=1
  144. if exclude is not None:
  145. print('exclude')
  146. elmt=random.choice(test_lst[5:])
  147. print(elmt)
  148. print(txt_dict[elmt])
  149. webdriver.ActionChains(driver).move_to_element(elmt).perform()
  150. elmt.click()
  151. # webdriver.ActionChains(driver).move_to_element(elmt).click().perform()
  152. time.sleep(5)
  153. if not found: #don't waste resources, pick a random link as long as it is ok
  154. attempt=0
  155. pick=''
  156. negativeflag=True
  157. while negativeflag==True:
  158. attempt+=1
  159. negativeflag=False
  160. pick = random.choice(elmts)
  161. href = pick.get_attribute('href')
  162. if href in blacklist:
  163. negativeflag=True
  164. '''try:
  165. content = pick.find_element(By.XPATH, "//em[@class='VwiC3b yXK7lf lyLwlc yDYNvb W8l4ac lEBKkf']/").text
  166. print(content)
  167. if "陳百欽" not in content:
  168. Exception
  169. except:
  170. print("Not Found")
  171. negativeFlag = True'''
  172. if attempt==100:
  173. print("Action Terminated")
  174. break
  175. webdriver.ActionChains(driver).move_to_element(pick).perform()
  176. webdriver.ActionChains(driver).move_to_element(pick).click().perform()
  177. #table.insert({'ranking':-1,'kw':kw,'results':numresults,'url':'','title':'未收錄','client':jsobj['cust']})
  178. except:
  179. print('exception')
  180. traceback.print_exc()
  181. driver.quit()
  182. # sys.exit()
  183. while True:
  184. try:
  185. cursor=db.query('select json from seo.seo_jobs where cust="啟翔" and plan="形象SEO" and json like "%陳百欽%" and (json like "%chinabiz.org.tw%" or json like "%vocus.cc%" or json like "%tw.news.yahoo.com%" or json like "%facebook.com%" or json like "%gvm.com.tw%" or json like "%fingermedia.tw%" or json like "%bg3.co%" or json like "%morningtaiwan.org%" or json like "%pchome.com.tw%" or json like "%twfile.com%" or json like "%twincn.com%" or json like "%theicons.net%" or json like "%nhu.edu.tw%") order by rand() limit 1')
  186. for c in cursor:
  187. js=json.loads(c['json'])
  188. prefix=js['prefix']
  189. postfix=js['postfix']
  190. domain=js['domain'][0]
  191. positive=js['positive']
  192. rnd=js['rnd']
  193. kw=''
  194. while '陳百欽' not in kw:
  195. kw=''
  196. kw1=random.choice(positive)
  197. kw2=random.choice(rnd)
  198. kw=kw1+" "+prefix+" "+kw2
  199. code='03'
  200. run_once({'domain':domain,'kw':kw, 'cust':'啟翔'})
  201. if driver is not None:
  202. try:
  203. driver.quit()
  204. except:
  205. pass
  206. cursor=None
  207. driver=None
  208. time.sleep(61)
  209. except:
  210. traceback.print_exc()
  211. print("Execution Error")
  212. if driver is not None:
  213. try:
  214. driver.quit()
  215. except:
  216. pass
  217. cursor=None
  218. driver=None
  219. time.sleep(20)