如何用lxml解析一个htmlpage与搞砸?

时间:2015-07-20 12:51:29

标签: python html html-parsing lxml lxml.html

我想用python中的lxml解析Nasa网站上的以下html:

    <p>
        <strong>Launch Date:</strong>1981-09-24<br/>
        <strong>Launch Vehicle:</strong> Delta<br/>
        <strong>Launch Site:</strong> Cape Canaveral, United States<br/>
        <strong>Mass:</strong> 550.0 kg<br/>
    </p>

使用python3的以下代码:     

from lxml.html import parse

page = parse("http://nssdc.gsfc.nasa.gov/nmc/spacecraftDisplay.do?id=1981-096A")

rows = page.xpath('//div[@class="urtwo"]/p')[0]
for element in rows:
    print(element.xpath("string()"))

但是头部后面的值是空的......:

Launch Date:

Launch Vehicle:

Launch Site:

Mass:

我认为必须对&lt;'/ strong&gt;执行某些操作或者&lt;'br /&gt;。

有人可以帮我找到解决方案吗?

1 个答案:

答案 0 :(得分:1)

如何迭代strong标记,将它们视为标签并将以下文本兄弟作为值:

rows = page.xpath('//div[@class="urtwo"]/p//strong')
for element in rows:
    label = element.text.strip()
    value = element.xpath("following-sibling::text()")[0].strip()

    print(label, value)

打印:

('Launch Date:', u'1981-09-24')
(u'Launch\xa0Vehicle:', u'Delta')
(u'Launch\xa0Site:', u'Cape Canaveral, United States')
('Mass:', u'550.0\xa0kg')