我正在尝试在Google colab中使用硒来刮擦YouTube视频的评论,但脚本会调用该异常。当我在本地计算机上运行相同的脚本时,它将起作用。 YouTube视频网站是动态的,我发现返回页面源内容未在colab上返回完整内容。但是,我不知道如何解决。
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import time
options = Options()
prefs = {"profile.managed_default_content_settings.images": 2}
options.add_experimental_option("prefs", prefs)
options.add_argument("--headless")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--window-size=2560x1440")
options.add_argument("start-maximised")
options.add_argument('--disable-gpu')
driver = webdriver.Chrome(chrome_options=options)
driver.get('https://www.youtube.com/watch?v=yIYKR4sgzI8')
time.sleep(10)
driver.execute_script('window.scrollTo(1, 500);')
time.sleep(10)
comment_div=driver.find_element_by_xpath('//*[@id="contents"]')
comments=comment_div.find_elements_by_xpath('//*[@id="content-text"]')
for comment in comments:
print(comment.text)
driver.close()
Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="contents"]"}
(Session info: headless chrome=80.0.3987.87)