【问题标题】:scraping youtube website using beautiful soup [duplicate]用漂亮的汤刮youtube网站[重复]
【发布时间】:2020-08-09 18:14:32
【问题描述】:

我正在使用以下代码抓取 youtube 搜索结果:

import requests
from bs4 import BeautifulSoup

url = "https://www.youtube.com/results?search_query=python"
response = requests.get(url)
soup = BeautifulSoup(response.content,'html.parser')
for each in soup.find_all("a", class_="yt-simple-endpoint style-scope ytd-video-renderer"):
    print(each.get('href'))

但它什么也没返回。这段代码有什么问题?

【问题讨论】:

  • 不请求该站点上的 BeautifulSoup 进程 JavaScript。您将需要一个不同的解决方案,您不仅要下载基本 html,还要执行 javascripts 并等待动态内容。你可以从 Selenium 开始,或者从 scrapy-splash 开始scrapy
  • 涉及javascript,美汤不执行。您必须使用 selenium 之类的东西从 youtube 中提取数据。相反,请查看 youtube-dl 从 youtube 搜索/提取/下载数据。

标签: python beautifulsoup


【解决方案1】:

BeatifulSoup 不是 Youtube 的正确工具抓取_ - Youtube 正在使用 JavaScript 生成大量内容。

您可以轻松测试它:

>>> import requests
>>> from bs4 import BeautifulSoup

>>> url = "https://www.youtube.com/results?search_query=python"
>>> response = requests.get(url)
>>> soup = BeautifulSoup(response.content,'html.parser')
>>> soup.find_all("a")
[<a href="//www.youtube.com/yt/about/en-GB/" slot="guide-links-primary" style="display: none;">About</a>, <a href="//www.youtube.com/yt/press/en-GB/" slot="guide-links-primary" style="display: none;">Press</a>, <a href="//www.youtube.com/yt/copyright/en-GB/" slot="guide-links-primary" style="display: none;">Copyright</a>, <a href="/t/contact_us" slot="guide-links-primary" style="display: none;">Contact us</a>, <a href="//www.youtube.com/yt/creators/en-GB/" slot="guide-links-primary" style="display: none;">Creators</a>, <a href="//www.youtube.com/yt/advertise/en-GB/" slot="guide-links-primary" style="display: none;">Advertise</a>, <a href="//www.youtube.com/yt/dev/en-GB/" slot="guide-links-primary" style="display: none;">Developers</a>, <a href="/t/terms" slot="guide-links-secondary" style="display: none;">Terms</a>, <a href="https://www.google.co.uk/intl/en-GB/policies/privacy/" slot="guide-links-secondary" style="display: none;">Privacy</a>, <a href="//www.youtube.com/yt/policyandsafety/en-GB/" slot="guide-links-secondary" style="display: none;">Policy and Safety</a>, <a href="/new" slot="guide-links-secondary" style="display: none;">Test new features</a>]

(请注意,您在屏幕截图中看到的链接不在列表中)

您需要为此使用另一种解决方案 - Selenium 可能是一个不错的选择。请查看此线程以获取详细信息Fetch all href link using selenium in python

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 2020-06-14
    • 2017-08-15
    • 1970-01-01
    相关资源
    最近更新 更多