tiny_click100.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. import random
  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 schedule
  12. import logging
  13. import sys
  14. from logging.handlers import SysLogHandler
  15. import socket
  16. import pandas as pd
  17. import socket
  18. import os
  19. _LOG_SERVER = ('hhh.ptt.cx', 514)
  20. logger = logging.getLogger('clickbot_100')
  21. handler1 = SysLogHandler(address=_LOG_SERVER,socktype=socket.SOCK_DGRAM)
  22. logger.addHandler(handler1)
  23. #logger.debug('[clickbot_100][清原]begin')
  24. hname=socket.gethostname()
  25. pid=str(os.getpid())
  26. logger.fatal('[clickbot_100]['+hname+']['+pid+']begin')
  27. def restart_browser():
  28. os.system('docker container restart headless-shell')
  29. time.sleep(9)
  30. chrome_options = webdriver.ChromeOptions()
  31. # chrome_options.add_argument("--incognito")
  32. chrome_options.add_argument("--headless")
  33. chrome_options.add_argument("--no-sandbox")
  34. chrome_options.add_argument("--disable-dev-shm-usage")
  35. chrome_options.add_argument("start-maximized")
  36. chrome_options.add_argument("user-data-dir=/tmp")
  37. chrome_options.debugger_address="127.0.0.1:9222"
  38. chrome98=r'C:\portable\webdriver\chrome98\chromedriver.exe'
  39. # chrome98=r'/root/drivers/98/chromedriver'
  40. driver = webdriver.Chrome(chrome_options=chrome_options,executable_path=chrome98)
  41. return driver
  42. def process_one():
  43. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/seo?charset=utf8mb4')
  44. lst=[]
  45. table=db['save_result']
  46. cursor=db.query('select term from selected_kw where client="清原" and term not in (SELECT distinct(keyword) FROM seo.save_result where url like "%taroboba-yuan.com%" and datediff(now(),dt)=0)')
  47. for c in cursor:
  48. lst.append(c['term'])
  49. term=random.choice(lst)
  50. print(term)
  51. logger.debug('[clickbot_100]['+term+']')
  52. driver=restart_browser()
  53. escaped_search_term=urllib.parse.quote(term)
  54. googleurl = 'https://www.google.com/search?q={}&num={}&hl={}'.format(escaped_search_term, 100,'zh-TW')
  55. print(googleurl)
  56. driver.get(googleurl)
  57. time.sleep(6)
  58. driver.save_screenshot('c:/tmp/test.png')
  59. fname=term.replace(' ','_')
  60. driver.save_screenshot('c:/tmp/seo/'+fname+'.png')
  61. df=pd.DataFrame()
  62. elmts=driver.find_elements_by_xpath("//div[@class='yuRUbf']/a")
  63. clickelmt=None
  64. cnt=1
  65. datadict={'搜尋詞':[],'結果標題':[],'結果網址':[],'結果名次':[]}
  66. for elmt in elmts:
  67. try:
  68. href=elmt.get_attribute('href')
  69. if 'taroboba-yuan.com' in href:
  70. clickelmt=elmt
  71. logger.debug('[clickbot_100]['+term+']['+str(cnt)+']')
  72. print(href)
  73. print(elmt.text)
  74. datadict['搜尋詞'].append(term)
  75. datadict['結果標題'].append(elmt.text)
  76. datadict['結果網址'].append(href)
  77. datadict['結果名次'].append(str(cnt))
  78. table.insert({'title':elmt.text,'url':href,'keyword':term,'dt':datetime.datetime.now(),'num':cnt})
  79. cnt+=1
  80. except:
  81. print('href2 exception')
  82. traceback.print_exc()
  83. if clickelmt:
  84. webdriver.ActionChains(driver).move_to_element(clickelmt).perform()
  85. webdriver.ActionChains(driver).move_to_element(clickelmt).click().perform()
  86. if len(datadict['結果標題'])<=0:
  87. print('None')
  88. driver.quit()
  89. sys.exit()
  90. df['搜尋詞']=datadict['搜尋詞']
  91. df['結果標題']=datadict['結果標題']
  92. df['結果網址']=datadict['結果網址']
  93. df['結果名次']=datadict['結果名次']
  94. df.to_excel('c:/tmp/seo/'+fname+".xls")
  95. driver.quit()
  96. process_one()
  97. parser = argparse.ArgumentParser()
  98. parser.add_argument('--loop')
  99. args = parser.parse_args()
  100. if args.loop:
  101. schedule.every(6).minutes.do(process_one)
  102. # schedule.every(0.4).minutes.do(process_one)
  103. while True:
  104. schedule.run_pending()
  105. time.sleep(1)