BeautifulSoup 去除指定的html样式属性


只想保留table的"colspan", "rowspan" 两个属性值,其余的属性都去掉

最开始想到的是正则匹配,发现太费劲

后面发现BeautifulSoup可以解决

# bs4 去除特定属性
def remove_css_tags():
    html_str = '''

产品

价格类型

价格

涨跌

单位

液氯

厂家

茌平信发

2000

+500

元/吨

东营华泰

2000

+500

元/吨

河北冀衡

2100

+500

元/吨

沧州聚隆

1800

+500

元/吨

江苏新浦

3300

0

元/吨

江苏富强

封盘

0

元/吨

内蒙吉兰泰

2800

0

元/吨

方大锦化

2000

+500

元/吨

市   场

山东地区

1800-2000

+300/500

元/吨

河北地区

1300/2100

+0/500

元/吨

江苏地区

2200-3100

0

元/吨

河南地区

1500

0

元/吨

辽宁地区

1800/2000

+500

元/吨

内蒙古地区

2800

0

元/吨

市场简述及后市预测

液氯:今日国内液氯市场低位反弹,市场呈上行趋势。华泰装置检修、大地装置降负荷,鲁中东部供应端减少,但鲁西区域企业复产,加之配套下游停车,市场处于博弈阶段,但企业存看涨心态,鉴于此,预计明日不排除有继续上行可能。

''' soup = BeautifulSoup(html_str, "html.parser") remove_html = remove_attrs(soup, whitelist=["colspan", "rowspan"]) # for tag in soup(): # for attr in tag.attrs: # print(attr) # if attr not in ["colspan", "rowspan"]: # del tag[attr] # for attribute in ["colspan", "rowspan"]: # del tag[attribute] print(remove_html)
#去除指定的css属性
def remove_attrs(soup, whitelist=["colspan", "rowspan"]):
    for tag in soup.findAll(True):
        for attr in [attr for attr in tag.attrs if attr not in whitelist]:
            del tag[attr]
    return soup