python - BeautifulSoup 获取给定类的 div 中所有不同的属性值

标签 python html beautifulsoup

假设我有一个带有这样的 div 的 html 文件:

<div class="message" title="user1"> <span> Hey </span> </div>
<div class="message" title="user1"> <span> It's me </span> </div>
<div class="message" title="user2"> <span> Hi </span> </div>
<div class="message" title="user3"> <span> Ola </span> </div>

如何获取所有发送消息的用户列表?

如果我使用find方法,我只能得到第一个用户,如果我使用find_all,我会得到user1两次。

我可以以某种方式一步完成它,而不删除 find_all 生成的列表中的重复项吗?

最佳答案

您可以使用自定义查找器功能

seen_users = set()
def users(tag):
    username = tag.get('title')
    if username and 'message' in tag.get('class', ''):
        seen_users.add(username)
        return True

tags = soup.find_all(users)
print(seen_users)  # {'user1', 'user2', 'user3'}

关于python - BeautifulSoup 获取给定类的 div 中所有不同的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53805958/

相关文章:

python - 我可以通过编译来提高 python 运行时吗?

javascript - CSS3 : change the color of the ball every time it bounces off the canvas wall

HTML 相对居中对齐

python - 索引 '[0]' 未提取正确的值?

python - 使用 BeautifulSoup 从 text/html 文档中获取干净的文本

python - BeautifulSoup 删除标签属性和文本内容

python - 如何向带有画线的小部件添加滚动条?

python - 如何使用 Python Dropbox API v2 读取 Dropbox 文件夹内的文件?

python - 带有大图像的 PIL "IOError: image file truncated"

html - 为什么伪元素的背景会隐藏父元素?