如何使用lxml解析html中的文本?

时间:2012-12-06 14:35:15

标签: python text xpath lxml

<p>
    Glassware veteran
    <strong>Corning </strong>
    (
    <span class="ticker">
      NYSE:
      <a class="qsAdd qs-source-isssitthv0000001" href="http://caps.fool.com/Ticker/GLW.aspx?source=isssitthv0000001" data-id="203758">GLW</a>
    </span>
    <a class="addToWatchListIcon qsAdd qs-source-iwlsitbut0000010" href="http://my.fool.com/watchlist/add?ticker=&source=iwlsitbut0000010" title="Add to My Watchlist"> </a>
    ) has fallen on hard times lately. Is it time to give up on the stock, or will Corning have a banana and a comeback?
</p>

我想得到“玻璃器皿老手”和“最近陷入困境的时候。是时候放弃股票了,还是康宁会吃香蕉还是卷土重来?”

使用代码

tnode = root.xpath("/p")
content = tnode.text

我只能得到“玻璃器皿老手”,为什么?

1 个答案:

答案 0 :(得分:0)

这样的事情可能会让你得到你想要的东西:

>>> tnode = root.xpath('/p')
>>> content = tnode.xpath('text()')
>>> print ''.join(content)

Glassware veteran

(


) has fallen on hard times lately. Is it time to give up on the stock, or will Corning have a banana and a comeback?
>>>

如果您想要所有文本节点,只需使用//text()代替text()

>>> print ' '.join([x.strip() for x in ele.xpath('//text()')])
Glassware veteran Corning ( NYSE: GLW    ) has fallen on hard times lately. Is it time to give up on the stock, or will Corning have a banana and a comeback?