使用LXML xml设置不带值的属性

时间:2015-06-22 11:34:46

标签: python lxml

我想:

<div data-a>

但LXML API似乎只给我这个:

<div data-a=''>

如何获得无价值属性?

令人讨厌的是,空白值和空值由LXML表示为空字符串。

设置无值无效。

In [19]: from lxml.html import fromstring, tostring

In [20]: b = fromstring('<body class="meow" data-a="haha" data-b data-x="">text-fef27e87389e466fb99b5421629323f6</body>')

In [21]: b.attrib
Out[21]: {'data-a': 'haha', 'data-x': '', 'data-b': '', 'class': 'meow'}

In [22]: b = fromstring('<body class="meow" data-a="haha" data-b data-x="">text-fef27e87389e466fb99b5421629323f6</body>')

In [23]: b.attrib
Out[23]: {'data-a': 'haha', 'data-x': '', 'data-b': '', 'class': 'meow'}

In [24]: b.attrib['data-y'] = None
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-1f55133e3dc4> in <module>()
----> 1 b.attrib['data-y'] = None

/usr/lib/python2.7/dist-packages/lxml/etree.so in lxml.etree._Attrib.__setitem__ (src/lxml/lxml.etree.c:58775)()

/usr/lib/python2.7/dist-packages/lxml/etree.so in lxml.etree._setAttributeValue (src/lxml/lxml.etree.c:19025)()

/usr/lib/python2.7/dist-packages/lxml/etree.so in lxml.etree._utf8 (src/lxml/lxml.etree.c:26460)()

TypeError: Argument must be bytes or unicode, got 'NoneType'


tag.attrib['data-a'] = None
TypeError: Argument must be bytes or unicode, got 'NoneType'

2 个答案:

答案 0 :(得分:2)

恕我直言,lxml正在展示预期的行为。没有值的属性使得格式不正确的XML,而不太合适的XML解析器不能生成格式不正确的XML:

答案 1 :(得分:1)

看起来您实际上是在尝试操作HTML而不是XML。如果是这样,则使用lxml.html而不是lxml.etree。

您正在尝试设置一个“布尔属性”,不要将其与“布尔值”混淆(请参阅boolean-attributes)。正如在其他答案中已经提到的那样,不允许使用布尔属性语法。e

但是,由于您似乎很想操纵HTML,因此您可以使用HTML元素而不是XML元素创建布尔属性。

200.21

输出

import unittest

import lxml.html

class HtmlBooleanAttribute(unittest.TestCase):

    def test_booleanAttribute(self):

        # !!! BE SURE TO CREATE AN ****HTML**** ELEMENT !!!
        div = lxml.html.Element('div')

        # Set a boolean attribute; omitting the value or providing None will
        # create a boolean attribute.
        div.set('data-a')
        div.set('data-b', None)

        # Setting the value to an empty will not give you a boolean attribute
        div.set('data-c', '')

        # Set a normal attribute for comparison
        div.set('class','big red')

        print
        print lxml.html.tostring(div)
        print

        # Note that 'data-a' will be a zero-length string
        print 'data-a = ', div.get('data-a')
        print 'type(data-a) = ', type(div.get('data-a'))
        print 'len(data-a) = ', len(div.get('data-a'))

        print

        print 'data-c = ', div.get('data-c')
        print 'type(data-c) = ', type(div.get('data-c'))
        print 'len(data-c) = ', len(div.get('data-c'))






if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()

请注意,data-a和data-b都是零长度的字符串,但是它们的打印方式不同。