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

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

问题描述

有没有办法在html中仅使用data属性来查找元素,然后获取该值?

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

 < ul data-bin =Sdafdo39> 

如何检索 Sdafdo39 对于具有 data-bin 属性的元素,整个html文档?

解决方案

<您可以使用 find_all 方法来获取所有标记,并根据在其属性中找到的data-bin进行过滤,从而获得实际标记。然后,我们可以简单地提取与它相对应的值,如下所示:

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


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

For example, with this line inside an html doc:

<ul data-bin="Sdafdo39">

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

解决方案

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天全站免登陆