【问题标题】:Whats the problem with my code it prints none when I use find() method and when I use findAll() method it prints empty array?我的代码有什么问题,当我使用 find() 方法时它不打印,当我使用 findAll() 方法时它打印空数组?
【发布时间】:2021-08-14 17:15:15
【问题描述】:
from bs4 import BeautifulSoup
import requests

yt_link = "https://www.youtube.com/watch?v=bKDdT_nyP54"

response = requests.get(yt_link)
soup = BeautifulSoup(response.content, 'html.parser')
title = soup.findAll('div', {'class': 'style-scope ytd-app'})
print(title)

它打印空数组[],如果我使用find()方法,那么它会打印None作为结果。

为什么会这样。请帮帮我,我被困在这里了。

【问题讨论】:

  • 未经测试,我敢打赌,其中之一是通过 javascript 加载的,您需要 Selenium。喜欢this

标签: python web web-scraping beautifulsoup python-requests


【解决方案1】:

是的,因为 youtube 使用 javascript 和动态内容渲染,所以很难找到标题,所以你可以尝试先打印 soup 并从中找到标题,所以在元中你可以找到标题提取它。它可能适用于任何网址

from bs4 import BeautifulSoup
import requests

yt_link = "https://www.youtube.com/watch?v=bKDdT_nyP54"

response = requests.get(yt_link)
soup = BeautifulSoup(response.content, 'html.parser')

title = soup.find('meta',attrs={"name":"title"})
print(title.get("content"))

输出:

Akon - Smack That (Official Music Video) ft. Eminem

【讨论】:

    【解决方案2】:

    由于 find() 方法如果没有找到则返回第一个匹配对象然后返回 None 并且 findAll() 方法如果没有找到则返回匹配对象的列表然后返回空列表。

    【讨论】:

      猜你喜欢
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 2016-04-19
      • 2020-10-25
      相关资源
      最近更新 更多