2017-04-03 58 views
1

整個HTML給定一個HTML輸入取計算的文本樣式,而無需渲染在python

html='''This is <b>Bold</b> or <strong>Also Bold</strong> or even <font style="text-weight: bold">Style Bold</font>''' 

我想僅過濾出大膽

注意,這個例子是簡化,我的真實使用情況下,我有幾百萬的文件要處理,有更多的結構和我不關心更多的HTML標籤。

result=["Bold","Also Bold","Style Bold"] 

的主要問題是,有幾種方法來設置字體粗細(HTML標籤/樣式表)

而且我不知道是否有一個Python包,可以使只有我在乎的標籤關於並觀察結果,或者唯一的辦法是編寫一個解析器我自己。

回答

1

我懷疑有選擇粗體文字的專用庫。然而,它與HTML解析器像BeautifulSoup很簡單:

from bs4 import BeautifulSoup 

input = """This is <b>Bold</b> or <strong>Also Bold</strong> or even <font style="text-weight: bold">Style Bold</font>""" 

soup = BeautifulSoup(input, "html.parser") 

bold = soup.select("b, strong, [style*=bold]") 

# > bold = [<b>Bold</b>, <strong>Also Bold</strong>, <font style="text-weight: bold">Style Bold</font>] 

bold_textonly = list(map(lambda tag: tag.text, bold)) # extract text from tags 

# > bold_textonly = ['Bold', 'Also Bold', 'Style Bold'] 

[style*=bold]font-weight: boldbolder匹配任何標記。如果你只想<font>標籤,選擇將font[style*=bold]

Working example at repl.it

有兩種創建某些特定的字體,如font-weight: 700左右粗體文本的其他方法。但是,這也很容易添加。

,當然,這僅適用於內聯樣式。由外部樣式選擇文本進行了大膽的將是更具挑戰性的......

1

我不認爲這是一個普遍的解決方案可靠,以涵蓋所有可能的使用情況下(如字體樣式可以通過CSS設置),但你可以得到接近它,並找到所有的bstrong元素,以及與「大膽」裏子font元素。

使用BeautifulSoup library工作實施例(使用searching function):

from bs4 import BeautifulSoup 


html = '''This is <b>Bold</b> or <strong>Also Bold</strong> or even <font style="text-weight: bold">Style Bold</font>''' 
soup = BeautifulSoup(html, "html.parser") 


def bold_only(tag): 
    is_b = tag.name == 'b' 
    is_strong = tag.name == 'strong' 
    is_bold_font = tag.name == 'font' and 'style' in tag.attrs and 'bold' in tag['style'] 

    return is_b or is_strong or is_bold_font 

print([bold.get_text() for bold in soup.find_all(bold_only)]) 

打印:

['Bold', 'Also Bold', 'Style Bold']