从特定的 html 标签打印文本,只有标签类名称。蟒蛇3

时间:2021-05-06 08:59:58

标签: html python-3.x

我需要一个代码“片段”(或您称之为),它打印出特定 html 类中的所有单词,而不是标签,而是类。

<h1 class="example">Hello people!</h1>

让我们说出于某种原因,网站的 HTML 看起来只是这样,我需要一个可以打印出 H1 TAG 内的内容但只能打印出类的代码。我试过研究这个,但没有得到任何有用的东西(虽然我不擅长研究)。

谢谢。

1 个答案:

答案 0 :(得分:1)

BeautifulSoup 可以为您做到这一点

from bs4 import BeautifulSoup
import requests
html_doc = '<h1 class="example">Hello people!</h1>'
# or, if you need to get the content from an http endpoint
# html_doc = requests.get(url_to_source).text

soup = BeautifulSoup(html_doc, 'html.parser')
for heading in soup.find_all(attrs={"class": "example"}):
    print(heading.string)