2012-02-14 11 views
5

Używam poniżej, aby uzyskać wszystkie treści HTML odcinka zapisać do bazy danychPython, lxml i usuwania tag zewnętrzną z użyciem lxml.html.tostring (EL)

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

opisie produktu ma tag, który wygląda tak:

<div id='productDescription'> 

    <THE HTML CODE I WANT> 

</div> 

Kod działa świetnie, daje mi cały kod html, ale w jaki sposób mogę usunąć zewnętrzną warstwę czyli <div id='productDescription'> i zamykającym tagiem </div>?

Odpowiedz

3

Można przekształcić każde dziecko indywidualnie ciąg:

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

Albo nawet więcej hackish sposób:

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

jeśli productDescriptiondiv div zawiera mieszany tekst/elementy treści, na przykład

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

można uzyskać zawartość (w ciągu) używając xpath('node()') przechodzenie:

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

Co to jest "łańcuch bazowy"? – nHaskins

0

Oto funkcja, która robi to, co chcesz.

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

Użyj wyrażeń regularnych.

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 
Powiązane problemy