通过漂亮的汤蟒

时间:2016-11-28 11:34:57

标签: python html beautifulsoup html-table font-size

我了解如何从此问题中获取特定divspan样式的文字:How to find the most common span styles

现在难以找到所有字体大小超过最常见字体大小的跨度样式吗?

我怀疑我应该使用正则表达式,但首先我需要提取特定的最常见字体大小?

另外,当条件为字符串时,如何确定“大于”?

2 个答案:

答案 0 :(得分:0)

这可能会对您有所帮助: -

    from bs4 import BeautifulSoup
    import re

    usedFontSize = [] #list of all font number used

    #Find all the span contains style 
    spans = soup.find_all('span',style=True)
    for span in spans:
        #print span['style']
        styleTag = span['style']
        fontSize = re.findall("font-size:(\d+)px",styleTag)
        usedFontSize.append(int(fontSize[0]))

    #Find most commanly used font size
    from collections import Counter
    count = Counter(usedFontSize)
    #Print list of all the font size with it's accurence.
    print count.most_common()

答案 1 :(得分:-1)

要使用BeautifulSoup查找字体大小大于最常见范围样式的所有范围样式,您需要解析已返回的每个CSS样式。

使用cssutils等库可以更好地解析CSS。这样,您就可以直接访问fontSize属性。

这将有一个12px这样的值,它不能自然地正确排序。要解决此问题,您可以使用natsort等库。

因此,首先将每个样式解析为css对象。同时保留每个跨度的所有汤的列表,以及样式的解析CSS。

现在使用fontSize属性作为使用natsort进行排序的键。这将根据字体大小为您提供正确排序的样式列表,最大值(使用reverse=True)。然后使用takewhile()创建列表中所有条目的列表,直到大小与最常见的条目匹配,从而产生大于最常见条目的条目列表。

from bs4 import BeautifulSoup
from collections import Counter
from itertools import takewhile    
import cssutils
import natsort

html = """
    <span style="font-family: ArialMT; font-size:12px">1</span>
    <span style="font-family: ArialMT; font-size:14px">2</span>
    <span style="font-family: ArialMT; font-size:1px">3</span>
    <span style="font-family: Arial; font-size:12px">4</span>
    <span style="font-family: ArialMT; font-size:18px">5</span>
    <span style="font-family: ArialMT; font-size:15px">6</span>
    <span style="font-family: ArialMT; font-size:12px">7</span>
    """

soup = BeautifulSoup(html, "html.parser")    
style_counts = Counter()
parsed_css_style = []       # Holds list of tuples (css_style, span)

for span in soup.find_all('span', style=True):
    style_counts[span['style']] += 1
    parsed_css_style.append((cssutils.parseStyle(span['style']), span))

most_common_style = style_counts.most_common(1)[0][0]
most_common_css_style = cssutils.parseStyle(most_common_style)
css_styles = natsort.natsorted(parsed_css_style, key=lambda x: x[0].fontSize, reverse=True)

print "Styles larger than most common font size of {} are:".format(most_common_css_style.fontSize)

for css_style, span in takewhile(lambda x: x[0].fontSize != most_common_css_style.fontSize, css_styles):
    print "  Font size: {:5}  Text: {}".format(css_style.fontSize, span.text)

在显示的示例中,最常用的字体大小为12px,因此还有3个大于此的条目如下:

Styles larger than most common font size of 12px are:
  Font size: 18px   Text: 5
  Font size: 15px   Text: 6
  Font size: 14px   Text: 2

要安装,您可能需要:

pip install natsort
pip install cssutils    

请注意,这确实假设您使用的字体大小在您的网站上是一致的,它无法比较不同的字体指标,只能比较数值。