我是python和xpath的新手。我正在尝试从 html 文件中打印标签"p"内的文本。我有这部分代码:
<section>
<p>Hello <br>nnn</br> <a href="google.com"> dfgdfg </a> World!</p>
</section>
我想打印:Hello nnn World!
和我使用的代码是:
for el in html.xpath('//section/p'):
print (el.text)
但打印的文字只是:你好任何人都可以帮我解决这个问题吗?
直接在 xpath 中使用 text()
:
for el in html.xpath('//section/p//text()'):
print (el)
检查//
说从当前p
内的所有节点获取所有文本。
要一起打印,请尝试:
print(''.join(html.xpath('//section/p//text()')))
尝试使用如下所示的XPath
'//section/p/text()'
来获取Hello nnn World!
:
for el in html.xpath('//section/p/text()'):
print (el, end='')
您也可以使用 text_content
.
for section_p in html.xpath('//section/p'):
print section_p.text_content()