2017-02-27 4 views
1

BeautifulSoupを使用して、要素からインライン高さと幅を削除しています。私は、(例えば)背景色を残したいと思うときインラインスタイルから高さと幅を削除する

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

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

しかし、私はこのような何かを処理については移動するかどうかはわかりません。画像のためにそれを解決するのは簡単でしたまたは高さまたは幅以外の他のスタイル属性であってもよい。

私はそれを行うと考えることができる唯一の方法は正規表現ですが、私はStackOverflowの精神が私のコンピュータから出てきて、私の最初の生まれを殺したようなものを示唆しました。

+0

もし私が正規表現を使用しなければならない場合、少し助けて頂ければ幸いです。 – thumbtackthief

+0

私はスタイルの属性_の内容をregexで使用しても問題はありませんが、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') 

タグの属性は、辞書オブジェクトである、あなたは辞書のようにそれを修正することができます。

GET項目:

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コードを投稿してテストします –

関連する問題