如何使用 lxml 获取斜体和非斜体文本

How to get italic and non italic text with lxml

我对 table 中的每一行都使用了这个命令,但我只得到了非斜体的文本。

name = ''.join(row.xpath('td[3]/a/text()'))

a 元素在 <em> </em 标签中有一些文本。

<td class="cardname"><a href="http://www.mtgotraders.com/store/PRM_Ball_Lightning_f.html"><em>Ball</em> <em>Lightning</em> *Foil*</a></td>

我想得到Ball Lightning *Foil*

这是你想要的吗?无论您使用 xpath 还是 css 选择器,结果总是一样的。试一试:

html_content='''
<td class="cardname"><a href="http://www.mtgotraders.com/store/PRM_Ball_Lightning_f.html">
<em>Ball</em> <em>Lightning</em> *Foil*</a></td>
'''
from lxml.html import fromstring

root = fromstring(html_content)
item = root.cssselect(".cardname a")[0].text_content().strip()
item_alternative = root.xpath("//*[@class='cardname']/a")[0].text_content().strip()

print(item)
print(item_alternative)

结果:

Ball Lightning *Foil*
Ball Lightning *Foil*