Python - 如何获取特定 div 的样式属性总数
Python - How to get total no of style attributes of a specific div
如何获得特定 div
的样式属性总数
例如:
<div class="div1" style="direction:rtl;text-align:center;clear:both;margin:.1em;margin-bottom:1em;">
此 div 样式有 5 个样式属性。
<div class="div2" style="direction:rtl;text-align:center;clear:both;margin:.1em;">
这个div样式有4个样式属性
使用 BeautifulSoup 解析器。
>>> soup = BeautifulSoup('''<div class="div1" style="direction:rtl;text-align:center;clear:both;margin:.1em;margin-bottom:1em;">''', 'html')
>>> len([i for i in soup.select('.div1')[0]['style'].split(';') if i])
5
from bs4 import BeautifulSoup
source = """
<div class="div1" style="direction:rtl;text-align:center;clear:both;margin:.1em;margin-bottom:1em;">
<div class="div2" style="direction:rtl;text-align:center;clear:both;margin:.1em;">
"""
soup = BeautifulSoup(source, 'lxml')
for div in soup.find_all('div'):
print div.get('style')
这会给你这样的输出:
direction:rtl;text-align:center;clear:both;margin:.1em;margin-bottom:1em;
direction:rtl;text-align:center;clear:both;margin:.1em;
现在这些是 str
个对象。您可以按 ;
拆分它们并根据需要设置格式。至于查找属性的数量,您可以这样处理:
for div in soup.find_all('div'):
print len(filter(None , div.get('style').split(';')))
输出:
5
4
如何获得特定 div
的样式属性总数例如:
<div class="div1" style="direction:rtl;text-align:center;clear:both;margin:.1em;margin-bottom:1em;">
此 div 样式有 5 个样式属性。
<div class="div2" style="direction:rtl;text-align:center;clear:both;margin:.1em;">
这个div样式有4个样式属性
使用 BeautifulSoup 解析器。
>>> soup = BeautifulSoup('''<div class="div1" style="direction:rtl;text-align:center;clear:both;margin:.1em;margin-bottom:1em;">''', 'html')
>>> len([i for i in soup.select('.div1')[0]['style'].split(';') if i])
5
from bs4 import BeautifulSoup
source = """
<div class="div1" style="direction:rtl;text-align:center;clear:both;margin:.1em;margin-bottom:1em;">
<div class="div2" style="direction:rtl;text-align:center;clear:both;margin:.1em;">
"""
soup = BeautifulSoup(source, 'lxml')
for div in soup.find_all('div'):
print div.get('style')
这会给你这样的输出:
direction:rtl;text-align:center;clear:both;margin:.1em;margin-bottom:1em;
direction:rtl;text-align:center;clear:both;margin:.1em;
现在这些是 str
个对象。您可以按 ;
拆分它们并根据需要设置格式。至于查找属性的数量,您可以这样处理:
for div in soup.find_all('div'):
print len(filter(None , div.get('style').split(';')))
输出:
5
4