如何解决使用beautifulsoup获取youtube视频的信息
我是python脚本的新手,我正在尝试使用beautifulsoup获取youtube视频的信息,例如标题,描述,观看次数和喜欢次数。在不使用Youtube API而是使用beautifulsoup的情况下,应该如何做到这一点。 现在,我单击检查,然后单击youtube视频的标题,
<h1 class="title style-scope ytd-video-primary-info-renderer">
<yt-formatted-string force-default-style="" class="style-scope ytd-video-primary-info-renderer">
Tucker: Kamala Harris may end up running the country</yt-formatted-string></h1>
我的代码是
# I also try use class as title style-scope ytd-video-primary-info-renderer
for i in soup.findAll('h1',{'class':'style-scope ytd-video-primary-info-renderer'}):
videoName.append(i)
但是它没有获得视频的标题。同样,这在获取视频说明以及喜欢和观看视频时不起作用。有人可以帮我找到如何使用beautifulsoup进行搜索的人吗?非常感谢!!!
解决方法
YouTube使用JavaScript,但是requests
不支持JavaScript。因此我们可以使用Requests-HTML之类的库来抓取页面。
使用pip install requests-html
安装它。
例如,此脚本将获得视频的标题:
from requests_html import HTMLSession
from bs4 import BeautifulSoup
video_url = "ENTER LINK"
# Initialize an HTML Session
session = HTMLSession()
# Get the html content
response = session.get(video_url)
# Execute JavaScript
response.html.render(sleep=3)
soup = BeautifulSoup(response.html.html,"lxml")
print("title:",soup.select_one('#container > h1').text)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。