2017-02-27 83 views
1

我使用BeautifulSoup從我的元素中刪除內聯高度和寬度。解決它的圖像很簡單:從內聯樣式中刪除高度和寬度

def remove_dimension_tags(tag): 
    for attribute in ["width", "height"]: 
     del tag[attribute] 
    return tag 

但我不知道如何去處理這樣的事情:

<div id="attachment_9565" class="wp-caption aligncenter" style="width: 2010px;background-color:red"> 

,當我要離開的背景顏色(例如)或除高度或寬度以外的任何其他樣式屬性。

我能想到的唯一方法就是使用正則表達式,但是上次我提出了這樣的想法,StackOverflow的精神從我的計算機中出來並殺死了我的第一胎。

+0

如果我_am_應該使用正則表達式...有一點幫助,將不勝感激。 – thumbtackthief

+0

我沒有看到使用正則表達式_on風格attribute_的內容有任何問題,但使用BeautifulSoup找到該屬性。 – Ben

回答

1

一個完整的步行通過的將是:

from bs4 import BeautifulSoup 
import re 

string = """ 
    <div id="attachment_9565" class="wp-caption aligncenter" style="width: 2010px;background-color:red"> 
     <p>Some line here</p> 
     <hr/> 
     <p>Some other beautiful text over here</p> 
    </div> 
    """ 

# look for width or height, followed by not a ; 
rx = re.compile(r'(?:width|height):[^;]+;?') 

soup = BeautifulSoup(string, "html5lib") 

for div in soup.findAll('div'): 
    div['style'] = rx.sub("", string) 

如其他人所述,使用正則表達式對實際值不是問題。

1

如果你願意,你可以使用正則表達式,但有一個更簡單的方法。

使用cssutils一個簡單的CSS解析

一個簡單的例子:

from bs4 import BeautifulSoup 
import cssutils 

s = '<div id="attachment_9565" class="wp-caption aligncenter" style="width: 2010px;background-color:red">' 

soup = BeautifulSoup(s, "html.parser") 
div = soup.find("div") 
div_style = cssutils.parseStyle(div["style"]) 
del div_style["width"] 
div["style"] = div_style.cssText 
print (div) 

輸出:

>>><div class="wp-caption aligncenter" id="attachment_9565" style="background-color: red"></div> 
-1
import bs4 

html = '''<div id="attachment_9565" class="wp-caption aligncenter" style="width: 2010px;background-color:red">''' 

soup = bs4.BeautifulSoup(html, 'lxml') 

標籤的屬性是一個字典對象,你可以修改它就像一個字典:

獲取項:

soup.div.attrs 

{'class': ['wp-caption', 'aligncenter'], 
'id': 'attachment_9565', 
'style': 'width: 2010px;background-color:red'} 

設置項:

soup.div.attrs['style'] = soup.div.attrs['style'].split(';')[-1] 

{'class': ['wp-caption', 'aligncenter'], 
'id': 'attachment_9565', 
'style': 'background-color:red'} 

使用正則表達式:

soup.div.attrs['style'] = re.search(r'background-color:\w+', soup.div.attrs['style']).group() 
+0

這隻適用於如果我知道屬性的順序和多少個。 – thumbtackthief

+0

雖然如此,如果高度和寬度以任意順序穿插任意數量的元素,這將不起作用。 – thumbtackthief

+0

@thumbtackthief發佈html代碼,我會測試它 –