2016-11-28 1 views
0

아름다운 수프 : How to find the most common span styles를 통해 가장 일반적인 것보다 더 큰 글꼴 크기와 모든 범위의 스타일을 찾기 나는이 질문에서 특정 <code>div</code> 또는 <code>span</code> 스타일에서 텍스트를 얻는 방법을 이해 파이썬

는 이제 어려움에 노력하고있다 가장 일반적인 글꼴 크기보다 큰 글꼴 크기로 모든 범위 스타일을 찾으십시오.

정규 표현식을 사용해야한다고 생각 합니다만, 가장 일반적인 글꼴 크기를 추출해야합니까?

또한 조건이 문자열 일 때 "보다 큼"을 어떻게 결정합니까?

+0

하나의리스트에 모든 스타일을 가져 와서 반복하고 모든 스타일의'font-size'를 하나의 배열에 저장하면됩니다. 당신은 더 큰 것을 찾을 수 있습니다. –

답변

0

이 당신을 도울 수 있습니다 : - 글꼴 BeautifulSoup로, 당신은 반환 된 각 CSS 스타일을 분석 할 필요가 사용하는 가장 일반적인 스팬 스타일보다 더 큰 크기로

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

모든 범위의 스타일을 찾을 수 있습니다.

CSS 구문 분석은 cssutils과 같은 라이브러리를 사용하는 것이 더 좋습니다. 이렇게하면 fontSize 속성에 직접 액세스 할 수 있습니다.

자연히 올바르게 정렬되지 않는 12px과 같은 값을 갖습니다. 이 문제를 해결하려면 natsort과 같은 라이브러리를 사용할 수 있습니다.

그래서 먼저 각 스타일을 CSS 개체로 구문 분석하십시오. 동시에 스타일에 대한 구문 분석 된 CSS와 함께 각 범위에 대한 모든 수프의 목록을 유지하십시오.

이제 Natsort를 사용하여 정렬 할 때 fontSize 속성을 키로 사용하십시오. 이렇게하면 가장 큰 글꼴 크기에 따라 스타일 목록을 올바르게 정렬 할 수 있습니다 (reverse=True 사용). 그런 다음 takewhile()을 사용하여 가장 일반적인 항목보다 크기가 큰 항목까지 목록의 모든 항목 목록을 작성하여 가장 일반적인 항목 목록보다 큰 목록을 만듭니다.

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 

은 아마 당신은해야합니다 설치하려면 :의 예에서

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) 

은 가장 일반적으로 사용되는 글꼴 크기는 이것보다 더 큰 3 개 다른 항목이 있으므로 다음과 같이 12px입니다

pip install natsort 
pip install cssutils  

사용 된 글꼴 크기가 웹 사이트에서 일관성이 있다고 가정합니다. 다른 글꼴 메트릭을 숫자 값으로 비교할 수는 없습니다.

+0

감사합니다 Martin, 내용을 캡처하기 위해 수프 함수에 글꼴 크기 정보를 다시 사용해야하므로 여전히 테스트 중입니다. 먼저 작은 질문부터, 왜! = 큰 것보다? 그것은 같지 않아야합니까? btw, 왜 아무도 클릭하지 않는 이유를 모르겠다. ..... –

+0

그 시점의 목록은 이미 가장 큰 것부터 가장 작은 것으로 정렬되었으므로'takewhile'은'12px와 일치 할 때까지 전체 목록에서 항목을 읽는 데 사용됩니다 '입장. –

+0

고마워 마틴, 글꼴 크기를 다시 수프 행으로 가져 오려고했습니다.AttributeError : 'ResultSet'객체에 'get'속성이 없습니다. –

관련 문제