在文本开头插入元素

时间:2016-05-13 11:17:00

标签: python lxml

我想在reverse_html之前插入footnote作为footnote.text的第一个元素,但却失败了。

我该怎么做?

#!/usr/bin/env python3

from unittest import TestCase, TestProgram

class T(TestCase):
    def test(self):
        try:
            from lxml.etree import fromstring, tostring, XMLParser
        except ImportError:
            raise
        p_start = r'<p id="n1">'
        p_text = r'description'
        p_end = r'</p>'
        p = p_start + p_text + p_end
        a = r'<a href="#r1">^</a>'
        parser = XMLParser(remove_blank_text=True)
        footnote, reverse_href = (fromstring(xml, parser) for xml in (p, a))
        self._transform(footnote, reverse_href)
        expected = self._expected(p_start, p_text, p_end, a)
        gotten = tostring(footnote).strip().decode()
        self.assertEqual(expected, gotten)
    @staticmethod
    def _transform(footnote, reverse_href):
        footnote.text = ' ' + footnote.text
        footnote.insert(0, reverse_href)
    @staticmethod
    def _expected(p_start, p_text, p_end, a):
        return p_start + a + ' ' + p_text + p_end

if __name__ == r'__main__':
    TestProgram()

1 个答案:

答案 0 :(得分:0)

  

“我想在reverse_html之前插入footnote footnote.text

lxml.etree模型中,这意味着将footnote.text移动为tail的{​​{1}}:

reverse_html

结果:

def _transform(footnote, reverse_href):
    reverse_href.tail = footnote.text
    footnote.text = ''
    footnote.insert(0, reverse_href)