2012-02-14 17 views
5

Estoy utilizando el siguiente para obtener todo el contenido HTML de una sección para guardar en una base de datosPython, lxml y la eliminación de etiqueta externa del uso de lxml.html.tostring (el)

el = doc.get_element_by_id('productDescription') 
lxml.html.tostring(el) 

La descripción del producto tiene una etiqueta que tiene este aspecto:

<div id='productDescription'> 

    <THE HTML CODE I WANT> 

</div> 

el código funciona muy bien, me da todo el código html pero no cómo quitar la capa externa es decir, el <div id='productDescription'> y la etiqueta de cierre </div>?

Respuesta

3

Se podría convertir a cada niño individualmente cadena:

text = el.text 
text += ''.join(map(lxml.html.tostring, el.iterchildren())) 

O en forma aún más hacker:

el.attrib.clear() 
el.tag = '|||' 
text = lxml.html.tostring(el) 
assert text.startswith('<'+el.tag+'>') and text.endswith('</'+el.tag+'>') 
text = text[len('<'+el.tag+'>'):-len('</'+el.tag+'>')] 
3

si su productDescriptiondiv div contiene texto mixto/elementos de contenido, por ejemplo,

<div id='productDescription'> 
    the 
    <b> html code </b> 
    i want 
</div> 

se puede obtener el contenido (en cadena) usando xpath('node()') recorrido:

s = '' 
for node in el.xpath('node()'): 
    if isinstance(node, basestring): 
     s += node 
    else: 
     s += lxml.html.tostring(node, with_tail=False) 
+2

¿Qué es 'basestring'? – nHaskins

0

Aquí es una función que hace lo que quiere.

def strip_outer(xml): 
    """ 
    >>> xml = '''<math xmlns="http://www.w3.org/1998/Math/MathML" xmlns:mml="http://www.w3.org/1998/Math/MathML" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/1998/Math/MathML   http://www.w3.org/Math/XMLSchema/mathml2/mathml2.xsd"> 
    ... <mrow> 
    ...  <msup> 
    ...  <mi>x</mi> 
    ...  <mn>2</mn> 
    ...  </msup> 
    ...  <mo> + </mo> 
    ...  <mi>x</mi> 
    ... </mrow> 
    ... </math>''' 
    >>> so = strip_outer(xml) 
    >>> so.splitlines()[0]=='<mrow>' 
    True 

    """ 
    xml = xml.replace('xmlns=','xmlns:x=')#lxml fails with xmlns= attribute 
    xml = '<root>\n'+xml+'\n</root>'#...and it can't strip the root element 
    rx = lxml.etree.XML(xml) 
    lxml.etree.strip_tags(rx,'math')#strip <math with all attributes 
    uc=lxml.etree.tounicode(rx) 
    uc=u'\n'.join(uc.splitlines()[1:-1])#remove temporary <root> again 
    return uc.strip() 
0

Usa regexp.

def strip_outer_tag(html_fragment): 
    import re 
    outer_tag = re.compile(r'^<[^>]+>(.*?)</[^>]+>$', re.DOTALL) 
    return outer_tag.search(html_fragment).group(1) 

html_fragment = strip_outer_tag(tostring(el, encoding='unicode')) # `encoding` is optionaly 
Cuestiones relacionadas