这一定是绝对的经典,但我在这里找不到答案。我正在使用 lxml cssselect 解析以下标记:
<li><a href="/stations/1"><span class="num">3</span> Detroit</a></li>
我想获取<li>
的内容标记没有 <span>
的内容标签。
目前我有:
stop_list = doc.cssselect('ol#stations li a')
start = stop_list[0].text_content().strip()
但这给了我 3 Detroit
.我怎样才能得到 Detroit
?
最佳答案
对于您的示例,我认为使用 XPath 比使用 CSS 更简洁、更容易:
>>> xml = '<li><a href="/stations/1"><span class="num">3</span> Detroit</a></li>'
>>> root = etree.fromstring(xml)
>>> print( root.xpath('/li/a/text()'))
[' Detroit']
>>> xml = '<li><a href="/stations/1">I <span>FooBar!</span> love <span class="num">3</span> Detroit</a></li>'
>>> root = etree.fromstring(xml)
>>> print( root.xpath('/li/a/text()'))
['I ', ' love ', ' Detroit']
>>> ' '.join([x.strip() for x in root.xpath('/li/a/text()')])
'I love Detroit'
关于python - lxml 经典 : Get text content except for that of nested tags?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8141956/