Pythonは、HTML幅のhegihtスタイル属性を削除します(HTMLタグから属性を削除します)



Python Removes Html Width Hegiht Style Attribute



通常、HTMLタグの属性を変更すると、正規表現に置き換えることができます。ただし、抜けやすいというデメリットがあります。徹底的なテストの後、利用可能な正規表現を書くことができます。 Pythonのlxmlモジュールを使用すると、通常のルールや優れたホイールを作成する必要がなくなります。これもlxmlに基づくbs4モジュールもあります。 lxmlからタグ属性を削除する方法は2つあります。サンプルコードを1つずつ記述します。

xpath

import lxml from HTMLParser import HTMLParser html_string = u''' ''' html = lxml.html.fromstring(html_string) for tag in html.xpath(u'//*[@style]'): tag.attrib.pop(u'style') for tag in html.xpath(u'//*[@height]'): tag.attrib.pop(u'height') for tag in html.xpath(u'//*[@width]'): tag.attrib.pop(u'width') print(HTMLParser().unescape(lxml.html.tostring(html)))

このメソッドは、htmlインスタンスのxpathを介してプロパティを取得し、それをポップして削除します。



掃除

import lxml.html.clean as clean safe_attrs = set(['src', 'alt', 'href', 'title']) cleaner = clean.Cleaner(safe_attrs=safe_attrs) html_string = u''' ''' cleaned_html = cleaner.clean_html(html_string) print(cleaned_html)

結果は次のとおりです。

BeautifulSoup

from BeautifulSoup import BeautifulSoup def _remove_attrs(soup): for tag in soup.findAll(True): tag.attrs = None return soup def example(): doc = 'test

junk



blah '
print 'Before: %s' % doc soup = BeautifulSoup(doc) clean_soup = _remove_attrs(soup) print ' After: %s' % clean_soup

参照:
https://stackoverflow.com/questions/7470333/remove-certain-attributes-from-html-tags
https://stackoverflow.com/questions/10037289/remove-class-attribute-from-html-using-python-and-lxml