Is it possible for xpath to return NULL if there is no text data?

I am currently trying to extract all the data from a table. Table data rows are formatted as <td headers="h1" align="left"></td>when there is no data.

Using a method etree.tostring()from the library lxmldisplays these elements as <td headers="h1" align="left"/>instead of formatting the source code.

Also, using xpathif I ran the code tree.path('//td[@headers="h1"]/text()'), the resulting list will not contain empty values ​​that have no data.

As I try to write these results to a CSV file, how to include NULL, i.e. ""when there is no data?

+4
source share
1 answer

//td[@headers="h1"] xpath , .text :

from lxml import etree

data = """
<table>
    <tr>
        <td headers="h1" align="left"></td>
        <td headers="h1" align="left">Text1</td>
        <td headers="h1" align="left"/>
        <td headers="h1" align="left">Text2</td>
        <td headers="h1" align="left"></td>
    </tr>
</table>
"""

tree = etree.fromstring(data)
print [element.text for element in tree.xpath('//td[@headers="h1"]')]

[None, 'Text1', None, 'Text2', None]

None:

print [element.text if element.text is not None else ''
       for element in tree.xpath('//td[@headers="h1"]')]

:

['', 'Text1', '', 'Text2', '']

.: '' node '() XPath?

+1

Source: https://habr.com/ru/post/1542787/


All Articles