odnochlen
Как удалить определенную разметку и оставить текст? Например, таблицы?
Как заменить больше 2 <br> подряд без текста между ними? Регекспами - элементарно.
# -*- coding: utf-8 -*-
import lxml.html
from lxml.html.clean import Cleaner
html = """
<html>
<body>
<div id="remove_table">
before table
<table>
<tr>
<td>11</td>
<td>12</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
</tr>
</table>
after table
</div>
<div id="remove_br">
line1<br/>
line2<br/>
text
<br/><br/><br/>
</div>
</body>
</html>
"""
# Как удалить определенную разметку и оставить текст? Например, таблицы?
cleaner = Cleaner(remove_tags=['table', 'td', 'tr'])
print cleaner.clean_html(html)
# Как заменить больше 2 <br> подряд без текста между ними?
doc = lxml.html.fromstring(html)
elements = doc.xpath('//br[count(preceding-sibling::br) >= 2]')
for el in elements:
if not el.tail:
el.getparent().remove(el)
print lxml.html.tostring(doc)
odnochlen
В чем разница между Element и lxml.etree._ElementTree и почему parse() возвращает tree, а document_fromstring() - корневой Element?
http://lxml.de/tutorial.html#the-elementtree-classAn ElementTree is mainly a document wrapper around a tree with a root node. It provides a couple of methods for parsing, serialisation and general document handling. One of the bigger differences is that it serialises as a complete document, as opposed to a single Element. This includes top-level processing instructions and comments, as well as a DOCTYPE and other DTD content in the document
odnochlen
Это баг?
Наверное нет, нужно новый элемент создавать.
odnochlen
Можно сделать как-то так?
E.BR(tail='text')
в конструкторе текст, аттрибуты или дети, придется писать на строчку больше
br = E.BR()
br.tail = 'text'
odnochlen
Сидишь над ней и думаешь - может ну его нах и уже регекспами все сделать?
В ситуации когда регекспы проще и понятней, почему бы их не использовать?
upd: if not el.tail
Согласен, что br проще регекспом, только для универсальности нужно будет учитывать разные варианты написания br: <br>, <br/>, <br />, </br>. Хотя можно перед заменой нормализовать все с помощью lxml.html.tostring.