yt_comment.py 3.8 KB

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