28

看到这个 html

<div>
    <p>
    <span class="abc">Monitor</span> <b>$300</b>
    </p>
    <a href="/add">Add to cart</a>
</div>
<div>
    <p>
    <span class="abc">Keyboard</span> $20 
    </p>
    <a href="/add">Add to cart</a>
</div>

使用 xpath 我想解析Monitor $300Keyboard $20. 我使用这个 xpath

 //div[a[contains(., "Add to cart")]]/p/text()

但它选择<span class="abc">Monitor</span> <b>$300</b>. 我不想要标签。如何仅获取文本?

4

1 回答 1

39

您要选择所有后代文本,而不仅仅是子文本:

//div[a[contains(., "Add to cart")]]/p//text()

p注意和text()那里的双斜线。

不过,这可能还会包含大量标签间空白,您需要将其清理干净。使用示例lxml

>>> import lxml.etree as ET
>>> tree = ET.fromstring('''<div>
... <div>
...     <p>
...     <span class="abc">Monitor</span> <b>$300</b>
...     </p>
...     <a href="/add">Add to cart</a>
... </div>
... <div>
...     <p>
...     <span class="abc">Keyboard</span> $20 
...     </p>
...     <a href="/add">Add to cart</a>
... </div>
... </div>''')
>>> tree.xpath('//div[a[contains(., "Add to cart")]]/p//text()')
['\n    ', 'Monitor', ' ', '$300', '\n    ', '\n    ', 'Keyboard', ' $20 \n    ']
>>> res = _
>>> [txt for txt in (txt.strip() for txt in res) if txt]
['Monitor', '$300', 'Keyboard', '$20']
于 2013-01-31T17:35:08.740 回答