【问题标题】:Python - How to get total no of style attributes of a specific divPython - 如何获取特定 div 的样式属性总数
【发布时间】:2016-05-19 02:31:08
【问题描述】:

如何获取特定 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个样式属性

【问题讨论】:

  • 获取样式,从;拆分,计数?

标签: python css web-scraping beautifulsoup urllib2


【解决方案1】:
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

【讨论】:

  • 您可以将filter 中的lambda x:x 替换为None。引用文档“如果函数为无,则假定身份函数,即删除所有为假的可迭代元素”
  • 是的。感谢您的建议。 lambda 功能在我潜意识里总是首先出现在我的脑海中。
【解决方案2】:

使用 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

【讨论】:

    猜你喜欢
    • 2011-11-02
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 2014-12-05
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    相关资源
    最近更新 更多