【问题标题】:Youtube comment use seleniumYoutube 评论使用硒
【发布时间】:2022-01-24 23:29:17
【问题描述】:
import subprocess
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options

subprocess.Popen(r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\chrometemp"') # 디버거 크롬 구동

option = Options()
option.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
driver = webdriver.Chrome('chromedriver', options = option)
url = 'https://www.youtube.com/watch?v=_XulUbBra5M'
driver.get(url)

driver.maximize_window() # 크롬 창 크기 최대화
driver.implicitly_wait(3) # 페이지 로드까지 3초간 기다림

heihgt = driver.execute_script(
    "return document.documentElement.scrollHeight"
)
# 기존 위치
stand_height = 0

while True:
    # 현재 높이
    current_height = driver.execute_script(
        "return document.documentElement.scrollHeight"
    )

    driver.execute_script(
        f"window.scrollTo(0, {stand_height});"  #스크롤 내리기
    )
    time.sleep(1)


    # 스크롤 내린 페이지의 높이
    new_page_height = driver.execute_script(
        "return document.documentElement.scrollHeight"
    )
    stand_height = heihgt

    heihgt = new_page_height
    time.sleep(1)

    driver.find_element(By.XPATH, "//*[@id='contenteditable-root']")

#driver.close()

我正在制作一个使用爬取来评论 cmets 的程序,但是当我使用 xpath 找到 cmets 的位置时,我收到以下错误:我不知道为什么。

selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{"method":"xpath","selector":"//*[@id='contenteditable-root']" } (会话信息:chrome=96.0.4664.110)

Python 不支持 driver.find_element_by_xpath ,它支持 driver.find(By.XPATH,) 。这会导致错误吗?请告诉我为什么

【问题讨论】:

  • 你能分享你正在处理的 youtube 页面和更多你的代码吗?
  • @Prophet 我上传了完整的代码。请帮帮我。
  • 我没有看到任何匹配 //*[@id='contenteditable-root'] 的元素...
  • 您是想写新评论还是阅读现有的 cmets?
  • @Prophet Tring 写一条新评论

标签: xpath


【解决方案1】:

用于插入新评论的输入元素最初并未加载到页面上。
要加载此元素,您需要向下滚动页面。
此外,要使实际的输入评论元素具有交互性,您首先需要单击另一个元素。
这应该有效:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = 'https://www.youtube.com/watch?v=_XulUbBra5M'
driver.get(url)
wait = WebDriverWait(driver, 20)

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "button.ytp-play-button")))
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id='simplebox-placeholder']"))).click()
wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id='contenteditable-root']"))).send_keys(your_comment_text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-03
    • 2021-08-25
    • 2016-09-11
    • 2012-01-31
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多