Ниже приведен пример, чтобы делать то, что вы хотите. Для HTML-документа Cleaner
является лучшим общим решением проблемы, чем использование strip_elements
, потому что в подобных случаях вы хотите удалить больше, чем просто тег <script>
; Вы также хотите избавиться от таких вещей, как onclick=function()
атрибуты других тегов.
#!/usr/bin/env python
import lxml
from lxml.html.clean import Cleaner
cleaner = Cleaner()
cleaner.javascript = True # This is True because we want to activate the javascript filter
cleaner.style = True # This is True because we want to activate the styles & stylesheet filter
print "WITH JAVASCRIPT & STYLES"
print lxml.html.tostring(lxml.html.parse('http://www.google.com'))
print "WITHOUT JAVASCRIPT & STYLES"
print lxml.html.tostring(cleaner.clean_html(lxml.html.parse('http://www.google.com')))
Вы можете получить список параметров, которые можно установить, в документации lxml.html.clean.Cleaner ; некоторые параметры вы можете просто установить на True
или False
(по умолчанию), а другие принимают список вроде:
cleaner.kill_tags = ['a', 'h1']
cleaner.remove_tags = ['p']
Обратите внимание, что разница между kill и remove:
remove_tags:
A list of tags to remove. Only the tags will be removed, their content will get pulled up into the parent tag.
kill_tags:
A list of tags to kill. Killing also removes the tag's content, i.e. the whole subtree, not just the tag itself.
allow_tags:
A list of tags to include (default include all).