【问题标题】:Webscraping Youtube pages网页抓取 Youtube 页面
【发布时间】:2021-03-10 20:29:53
【问题描述】:

我正在尝试通过链接从网络上抓取 youtube 频道名称。但我得到错误代码:

title = response.find_all('div', class_= "style-scope ytd-channel-name")
AttributeError: 'Response' object has no attribute 'find_all'

网站链接:https://www.youtube.com/channel/UCHOgE8XeaCjlgvH0t01fVZg

代码:

url = 'https://www.youtube.com/channel/UCHOgE8XeaCjlgvH0t01fVZg'
response = requests.get(url)

title = response.find_all('div', class_= "style-scope ytd-channel-name")
soup = BeautifulSoup(title.text, 'lxml')
print(soup)

谢谢!

【问题讨论】:

  • 你知道错误是什么意思吗?
  • 不,我一开始以为这意味着它无法找到该类的任何元素。但是测试其他人的代码我得到了与属性相同的错误
  • 这意味着该方法对于您从中调用它的对象不存在。变量response没有find_all方法,调用时会报错。
  • 嗯好吧。但是解决方法是什么?我认为 BeautifulSoup 能够找到某个类的所有元素
  • 如果答案有帮助,请点赞和/或标记为答案。如果没有,我很乐意解决。

标签: python html python-3.x web-scraping youtube


【解决方案1】:

我们可以使用它。

from requests_html import HTMLSession
from bs4 import BeautifulSoup as bs # importing BeautifulSoup


video_url = "https://www.youtube.com/channel/UCHOgE8XeaCjlgvH0t01fVZg"
# init an HTML Session
session = HTMLSession()
# get the html content
response = session.get(video_url)
# execute Java-script
response.html.render(sleep=1)
# create bs object to parse HTML
soup = bs(response.html.html, "html.parser")
name = soup.find('yt-formatted-string', class_='style-scope ytd-channel-name')
print(name.text)

输出:-

TheTekkitRealm

【讨论】:

    【解决方案2】:

    以下代码返回 div:

    url = "https://www.youtube.com/channel/UCHOgE8XeaCjlgvH0t01fVZg"
    req = requests.get(url)
    soup = BeautifulSoup(req.text, "html.parser")
    print(soup.div)
    

    返回的值可以通过“汤”来改变。值(例如,soup.title)。

    我链接到文档是因为我认为它对您也很有用: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#

    【讨论】:

    • 这不是问题的答案。更像是一个建议。在我看来。
    • 另外,这也行不通。 YT 数据大部分是 js 渲染的。。BeautifulSoup 不行。
    猜你喜欢
    • 2021-12-02
    • 1970-01-01
    • 2017-01-16
    • 2020-06-18
    • 2019-07-25
    • 2020-03-06
    • 2018-03-20
    • 1970-01-01
    相关资源
    最近更新 更多