在 YouTube 上查找 BeautifulSoup 和 Python 的链接

Finding links on YouTube with BeautifulSoup and Python

我正在使用 Beautiful Soup 在 YouTube 上进行网络抓取。 我的目标是从 YouTube 搜索页面找到所有视频链接:

response = urllib.request.urlopen("https://www.youtube.com/results?search_query=stfu")
soup = BeautifulSoup(response, "html.parser")

我正在搜索这个元素:

<a id="video-title" class="yt-simple-endpoint style-scope 
ytd-video-renderer" title="PINK GUY - STFU" 
href="/watch?v=OLpeX4RRo28" ...

我搜索了所有“a”标签元素,但只找到了几个:

for a in soup.findAll('a'):
    print(a)

结果链接似乎来自“帮助”部分或类似内容,而不是正文:

    <a href="https://www.youtube.com/about/" slot="guide-links-primary" style="display: none;">Información</a>
<a href="https://www.youtube.com/about/press/" slot="guide-links-primary" style="display: none;">Prensa</a>
<a href="https://www.youtube.com/about/copyright/" slot="guide-links-primary" style="display: none;">Derechos de autor</a>
<a href="/t/contact_us" slot="guide-links-primary" style="display: none;">Contacto</a>
<a href="https://www.youtube.com/creators/" slot="guide-links-primary" style="display: none;">Creadores</a>

当我打印所有 soup 对象以检查响应时,我注意到视频信息应该是空的地方:

<div class="video-skeleton">
<div class="video-details">
<div class="thumbnail skeleton-bg-color"></div>
<div class="details flex-1">
<div class="video-title text-shell skeleton-bg-color"></div>
<div class="video-meta text-shell skeleton-bg-color"></div>

这是我的链接应该在的地方,但里面什么也没有。

感谢您的帮助!

那是因为您正在发出 HTTP 请求,而 youtube 使用 JavaScript 呈现视频数据。为了能够解析 JS 内容,你必须使用支持发出请求然后用 JS 渲染它的库。

您可以使用 youtube api 检索 Youtube 搜索结果。许多编程语言的示例可用:https://github.com/youtube/api-samples