我需要一个代码“片段”(或您称之为),它打印出特定 html 类中的所有单词,而不是标签,而是类。
<h1 class="example">Hello people!</h1>
让我们说出于某种原因,网站的 HTML 看起来只是这样,我需要一个可以打印出 H1 TAG 内的内容但只能打印出类的代码。我试过研究这个,但没有得到任何有用的东西(虽然我不擅长研究)。
谢谢。
答案 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)