的Xpath仅获得第一个HTML标记之后文本
问题描述:
<div class="text">
<h1>Headerh1</h1>
Text1 <br/> after header1
<h3>Headerh3.1</h3>
Text2 <br/> after header3.1
<h3>Headerh3.2</h3>
Text3 <br/> after header3.2
<h3>Headerh3.3</h3>
Text4 <br/> after header3.3
</div>
如何使用后 //div[@class='text']/text()[count(preceding-sibling::h1)=1]
回归文本“头1后text1”中忽略<br/><br/>
作为 第一H1后得到的文本所有标题。 <br>
可以0+倍
答
尝试使用下面的XPath第一h3
前右应该返回位于的div
所有文本节点:
//div[@class='text']/h3[1]/preceding-sibling::text()
答
我假定这是您的目录中的HTML,这就是所谓 demo.html
from bs4 import BeautifulSoup
with open("demo.html") as f:
data = f.read()
soup = BeautifulSoup(data, 'html.parser')
f.close()
#to get the text after h1 tag
h1 = soup.find('h1').text
#to get the text after all h3 tags
h3 = [i.text for i in soup.findAll('h3')]
输出将是Unicode格式 为如:
h3 = [u'Headerh3.1', u'Headerh3.2', u'Headerh3.3']
将它们转换成普通字符串为此
h3 = [i.text.encode('utf-8') for i in soup.findAll('h3')]
h1 = soup.find('h1').text.encode('utf-8')
+0
我需要得到头H1之间的文本,H3“文本1
头1后” –
dMazay
它的工作原理,但是如果在div之后是文本,它也会被返回。是否可以在h3之间但在h1之后添加条件文本? – dMazay
是的。这一个应该做的技巧'/ div [@ class ='text']/h3 [1]/preceding-sibling :: text()[./ preceding-sibling :: h1]' – Andersson
已解决。有用! – dMazay