yt_comment.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. import time
  2. import numpy as np
  3. import pandas as pd
  4. import requests
  5. import os
  6. from selenium import webdriver
  7. from selenium.webdriver.common.by import By
  8. from selenium.webdriver.support.ui import WebDriverWait
  9. from selenium.webdriver.support import expected_conditions as EC
  10. from selenium.webdriver.common.keys import Keys
  11. from selenium.common.exceptions import NoSuchElementException
  12. from selenium_stealth import stealth
  13. import redis
  14. import json
  15. import random
  16. import fire
  17. def open_driver(profile_file):
  18. op = webdriver.ChromeOptions()
  19. # op.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
  20. # op.add_argument('--headless')
  21. op.add_argument('--disable-dev-shm-usage')
  22. op.add_argument('--no-sandbox')
  23. op.add_argument(r'user-data-dir=C:\Users\Administrator\AppData\Local\Google\Chrome\User Data')
  24. op.add_argument(f"profile-directory={profile_file}")
  25. op.add_experimental_option("excludeSwitches", ["enable-automation"])
  26. op.add_experimental_option('useAutomationExtension', False)
  27. driver = webdriver.Chrome(options=op,
  28. executable_path=r'C:\Users\Administrator\Downloads\chromedriver_win32 (4)\chromedriver')
  29. # stealth(driver,
  30. # languages=["en-US", "en"],
  31. # vendor="Google Inc.",
  32. # platform="Win32",
  33. # webgl_vendor="Intel Inc.",
  34. # renderer="Intel Iris OpenGL Engine",
  35. # fix_hairline=True,
  36. # )
  37. time.sleep(5)
  38. # driver.get("https://www.youtube.com/watch?v=eFZckOTi24c")
  39. # driver.find_element(By.XPATH,'// *[ @ id = "openid-buttons"] / button[1]').click()
  40. return driver
  41. def comment_page(driver, url, comment):
  42. if len(url) == 0:
  43. print('Youtube Comment Bot: Finished!')
  44. return []
  45. # url = urls.pop()
  46. driver.get(url)
  47. print(url)
  48. driver.implicitly_wait(1)
  49. if not check_exists_by_xpath(driver, '//*[@id="movie_player"]'):
  50. return comment_page(driver, url, random_comment())
  51. time.sleep(4)
  52. driver.execute_script("window.scrollTo(0, 600);")
  53. if not check_exists_by_xpath(driver, '//*[@id="simple-box"]/ytd-comment-simplebox-renderer'):
  54. return comment_page(driver, url, random_comment())
  55. if check_exists_by_xpath(driver, '//*[@id="contents"]/ytd-message-renderer'):
  56. return comment_page(driver, url, random_comment())
  57. WebDriverWait(driver, 20).until(
  58. EC.presence_of_element_located((By.CSS_SELECTOR, "ytd-comments ytd-comment-simplebox-renderer")))
  59. driver.find_element_by_css_selector("ytd-comments ytd-comment-simplebox-renderer div#placeholder-area").click()
  60. driver.implicitly_wait(5)
  61. driver.find_element_by_xpath('//*[@id="contenteditable-root"]').send_keys(comment)
  62. driver.find_element_by_xpath('//*[@id="contenteditable-root"]').send_keys(Keys.CONTROL, Keys.ENTER)
  63. post = WebDriverWait(driver, 15).until(
  64. EC.element_to_be_clickable((By.CSS_SELECTOR, 'ytd-comments ytd-comment-simplebox-renderer'))
  65. )
  66. post.click()
  67. r = np.random.randint(2, 5)
  68. time.sleep(r)
  69. driver.quit()
  70. return comment_page(driver, url, random_comment())
  71. def random_comment():
  72. # You can edit these lines=======
  73. # df = pd.read_excel('/Users/zooeytsai/Downloads/yt留言.xlsx')
  74. # messages = df['文字']
  75. r = redis.Redis(host='db.ptt.cx', port=6379, db=0, password='choozmo9')
  76. js = r.get('yt_comment')
  77. messages = json.loads(js)
  78. # ===============================
  79. r = np.random.randint(0, len(messages))
  80. print(messages[r])
  81. return messages[r]
  82. def check_exists_by_xpath(driver, xpath):
  83. try:
  84. driver.find_element_by_xpath(xpath)
  85. except NoSuchElementException:
  86. return False
  87. return True
  88. class JParams(object):
  89. def get(self, profile):
  90. print(profile)
  91. r = redis.Redis(host='db.ptt.cx', port=6379, db=0, password='choozmo9')
  92. js = r.get('yt_video')
  93. jsobj = json.loads(js)
  94. videoId = random.choice(jsobj)
  95. url = f"https://www.youtube.com/watch?v={videoId}"
  96. driver = open_driver(profile)
  97. comment_page(driver, url, random_comment())
  98. if __name__ == '__main__':
  99. fire.Fire(JParams)