bs4 中的 Soup.find 无法从 h1 标签中抓取,但适用于所有其他 HTML 标签

问题描述 投票:0回答:1

我在使用 BeautifulSoup 4 时遇到问题。我的代码运行良好,然后开始出错,无法再从 h1 标签收集内部文本。奇怪的是,它与所有其他 HTML 标签完美配合。

这是我如何将它用于网页上每个元素的模板:

scraped = soup.find('h1', attrs={'class': 'class_name'}).decode_contents()

返回:

 

我不知道为什么它不与h1标签配合。有人遇到过这个问题吗?请帮忙!

python web-scraping beautifulsoup html-parsing html5lib
1个回答
0
投票

看源码,没有

<h1>
class="class_name"
。但您可以尝试仅获取
<h1>
标签(不指定任何类):

import requests
from bs4 import BeautifulSoup

url = "https://www.complex.com/music/a/brad-callas/peanut-butter-wolf-reminisces-mf-doom-madvillainy"

soup = BeautifulSoup(requests.get(url).content, "html.parser")
print(soup.h1.text)

打印:

Peanut Butter Wolf Reminisces on MF DOOM Making 'Madvillainy' on Album's 20th Anniversary
© www.soinside.com 2019 - 2024. All rights reserved.