我刚开始使用python脚本,我尝试用漂亮的汤来获取youtube视频的标题、描述、浏览次数和赞数等信息。如果不使用Youtube API,而使用漂亮的汤,我该如何做到呢?现在我点击检查,点击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)
但它没有得到视频的标题。此外,这不适用于获取视频描述和维都喜欢和视图。有人能帮我找出怎样才能找到那些使用漂亮汤的吗?非常感谢!
发布于 2020-08-13 20:47:17
YouTube使用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)
https://stackoverflow.com/questions/63402280
复制相似问题