如何从 BeautifulSoup4 中的 html 标签中找到特定的数据属性? [英] How find specific data attribute from html tag in BeautifulSoup4?

查看:31
本文介绍了如何从 BeautifulSoup4 中的 html 标签中找到特定的数据属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法只使用 html 中的 data 属性找到一个元素,然后获取那个值?

Is there a way to find an element using only the data attribute in html, and then grab that value?

例如,在 html 文档中使用这一行:

For example, with this line inside an html doc:

<ul data-bin="Sdafdo39">

如何通过在整个 html 文档中搜索具有 data-bin 属性的元素来检索 Sdafdo39?

How do I retrieve Sdafdo39 by searching the entire html doc for the element that has the data-bin attribute?

推荐答案

您可以使用 find_all 方法获取所有标签,并根据在其属性中找到的data-bin"过滤将得到我们得到它的实际标签.然后我们就可以简单的提取它对应的值了,像这样

You can use find_all method to get all the tags and filtering based on "data-bin" found in its attributes will get us the actual tag which has got it. Then we can simply extract the value corresponding to it, like this

from bs4 import BeautifulSoup
html_doc = """<ul data-bin="Sdafdo39">"""
bs = BeautifulSoup(html_doc)
print [item["data-bin"] for item in bs.find_all() if "data-bin" in item.attrs]
# ['Sdafdo39']

这篇关于如何从 BeautifulSoup4 中的 html 标签中找到特定的数据属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆