python - 如何在 Python 中使用 Selenium 在 Chrome 上向下滚动 Youtube channel

标签 python selenium web-scraping youtube

我正在尝试向下滚动 YouTube channel 的“视频”选项卡,以便获取该 channel 中所有视频的链接。我在 Python 3 中使用 Selenium 模块,使用 Google Chrome 作为浏览器。这是我的类中执行此部分的方法(在我调用 self.driver.get(CHANNEL_URL) 之后立即调用它)

def get_video_links(self):
    xpath = '/html/body/ytd-app/div/ytd-page-manager/ytd-browse/ytd-two-column-browse-results-renderer/div[1]/ytd-section-list-renderer/div[2]/ytd-item-section-renderer/div[3]/ytd-grid-renderer/div[1]/ytd-grid-video-renderer/div[1]/div[1]/div[1]/h3/a'
    elements = self.driver.find_elements_by_xpath(xpath)
    last_result = 0
    curr_result = len(elements)
    while curr_result != last_result:
        self.driver.find_element_by_tag_name('body').send_keys(Keys.END)
        self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(3)
        elements = self.driver.find_elements_by_xpath(xpath)
        last_result = curr_result
        curr_result = len(elements)
    video_links = [elem.get_attribute('href') for elem in elements]
    return video_links
这目前返回 60 个 url,而不滚动则得到 30 个 url。然而,我正在抓取的 channel 有大约 150 个视频。我已经成功手动滚动,所以我知道元素查找部分有效。我试过thisthis但他们只给我 30 个网址,而且我没有看到浏览器上发生任何滚动。

最佳答案

您可以使用 JavaScript 在 selenium 中向下滚动。

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
取自 selenium docs.
如果您只想下载 channel 制作的所有视频,youtube-dl是更好的工作。
您所要做的就是从控制台运行 youtube-dl 并为您要下载的 channel 添加 channel ID。
$ youtube-dl "[INSERT CHANNEL-ID]"
它也适用于播放列表和单个视频,甚至支持其他网站。

关于python - 如何在 Python 中使用 Selenium 在 Chrome 上向下滚动 Youtube channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63589233/

相关文章:

python - Paypal 批量付款 - Python - 访问被拒绝

python - 为什么 lxml 不允许在整个 ElementTree 上使用相对 XPath 表达式?

javascript - WebDriverIO Selenium 将命令行参数从 config.js 文件传递​​到 Chrome

google-chrome - 调试 "Element is not clickable at point"错误

python - 无法测量列表中每个项目的频率

python - Python 权限被拒绝错误

python - 如何从立体声获取深度图-KITTI数据集

c# - 为什么 Selenium 会超时?

python - 如何从通过 JavaScript 加载的页面的 XHR 请求中自动检索请求 URL(对于 python)

excel - VBA : how to connect MSXML2. XMLHTTP60 对 IHTMLDocument(iframe) 的响应