首页 > 解决方案 > BeautifulSoup Python 得到一个名为“title”的元素

问题描述

所以我有以下HTML:

<span title="总播放数236819" class="view">23.7万播放&amp;nbsp;·&nbsp;</span>

我只想要'236819'。

我创建了 BeautifulSoup 对象和代码:

views = soup.findAll('span', class_ = 'view')

我如何添加到这个/从中删除以获得我想要的位?

谢谢!

标签: pythonbeautifulsoup

解决方案


您可以使用例如re模块从属性中仅提取数字"title"

import re
from bs4 import BeautifulSoup

html_doc = (
    """<span title="总播放数236819" class="view">23.7万播放&amp;nbsp;·&nbsp;</span>"""
)

soup = BeautifulSoup(html_doc, "html.parser")

views = soup.findAll("span", class_="view")

for view in views:
    print("".join(re.findall(r"\d+", view["title"])))   # <-- find only digits in "title" attribute

印刷:

236819

推荐阅读