2017-02-27 85 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代码,我会测试它 –