我有一个从<table>
<td align="center" valign="top">
<a href="ConfigGroups.aspx?cfgID=451161&prjID=11778&grpID=DTST"
target="_blank">
5548U
</a><br/>Power La Vaca<br/>(M8025K)<br/>Linux 4.2.x.x<br/>
</td>
我正在尝试从此元素(包括空格)中提取“55488 Power La Vaca(8025K)Linux 4.2.x.x”。
import lxml.etree as ET
td_html = """
<td align="center" valign="top">
<a href="ConfigGroups.aspx?cfgID=451161&prjID=11778&grpID=DTST"
target="_blank">
5548U
</a><br/>Power La Vaca<br/>(M8025K)<br/>Linux 4.2.x.x<br/>
</td>
"""
td_elem = ET.fromstring(td_html)
fail_1 = td_elem.find('a').text + td_elem.text
print "FAIL_1", fail_1
print "FAIL_2"
for elem in td_elem.iterchildren():
print elem.tag, elem.text
$ python textxml.py
FAIL_1
5548U
FAIL_2
a
5548U
br None
br None
br None
br None
$
令人羞愧的是,我不得不问这个问题,因为它似乎不应该很难。
如何从td_elem
元素(包括空格)中提取“Power La Vaca(8025K)Linux 4.2.x.x”?
请,没有正则表达式解决方案。
显式解决方案(使用Finn的itertext()
建议):
import lxml.etree as ET
td_html = """
<td align="center" valign="top">
<a href="ConfigGroups.aspx?cfgID=451161&prjID=11778&grpID=DTST"
target="_blank">
5548U
</a><br/>Power La Vaca<br/>(M8025K)<br/>Linux 4.2.x.x<br/>
</td>
"""
td_elem = ET.fromstring(td_html)
print "SUCCESS", ' '.join([txt.strip() for txt in td_elem.itertext()])
答案 0 :(得分:3)
我知道必须有一个更好的方法,但这有效。
link = td_elem.find('a').text.strip()
text = ''.join(td_elem.itertext()).strip()
text.split(link)[1]
输出 Power La Vaca(M8025K)Linux 4.2.x.x
更新:
如果您想要空格代替<br>
s
' '.join(map(str, [el.tail for el in td_elem.iterchildren() if el.tail]))
map
str
实际上并不需要它,但我可以设想其他值。
答案 1 :(得分:3)
使用XML时,即使在Python中,我也喜欢尝试使用可用的特定于域的工具。对于解析XML的位,XPath是适合我的。
>>> td_elem = ET.fromstring(td_html)
>>>
>>> # Use XPath to grab just the text nodes under <td/>,
>>> # ignoring any text nodes in child nodes of <td/> (i.e., <a...>5548U</a>)
>>> print(td_elem.xpath('/td/text()'))
['\n ', 'Power La Vaca', '(M8025K)', 'Linux 4.2.x.x', '\n']
>>>
>>> # Make it a little cleaner
>>> ' '.join(x.strip() for x in td_elem.xpath('/td/text()'))
' Power La Vaca (M8025K) Linux 4.2.x.x '
>>>
>>> # Just for reference, grab all text nodes with '//'
>>> ' '.join(x.strip() for x in td_elem.xpath('/td//text()'))
' 5548U Power La Vaca (M8025K) Linux 4.2.x.x '