如何从标签中获取文本,其中属性由
或标签分隔?例如,对于下面代码中的“Adresa:”,我试图获取地址:soup.find('strong', text = 'Adresa:')
但我不知道如何在 <strong>Adresa:</strong>
之后获取文本和之前 <strong>Telefón:</strong>
.
输出应该是:Adresa: Obecný úrad Nána, Madáchova 32, 943 60 Nána
代码示例如下:
<p>
<strong>Adresa:</strong>Obecný úrad Nána<br></br>Madáchova 32<br></br>943 60 Nána<br></br><br></br><strong>Telefón:</strong>036/759 70 06<br></br><strong>Fax:</strong>036/7597 007<br></br><strong>Web:</strong><a href="http://www.obecnana.sk"></a><br></br>
</p>
最佳答案
思路是通过文本找到strong
标签,然后使用find_next_siblings()
, 找到所有兄弟标签并在下一个 strong
标签处停止:
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup, NavigableString
data = u"""
<p>
<strong>Adresa:</strong>Obecný úrad Nána<br></br>Madáchova 32<br></br>943 60 Nána<br></br><br></br>
<strong>Telefón:</strong>036/759 70 06<br></br>
<strong>Fax:</strong>036/7597 007<br></br>
<strong>Web:</strong><a href="http://www.obecnana.sk"></a><br></br>
</p>
"""
soup = BeautifulSoup(data)
address = soup.find(text='Adresa:')
texts = []
for item in address.parent.find_next_siblings():
if item.name == 'strong':
break
text_before = item.previous_sibling
if isinstance(text_before, NavigableString):
texts.append(text_before)
print ' '.join(texts)
它打印:
Obecný úrad Nána Madáchova 32 943 60 Nána
然后,您可以将代码提取到一个漂亮的可重用函数中:
def get_section_text(text):
section = soup.find(text=text)
if not section:
raise ValueError("Section not found")
texts = []
for item in section.parent.find_next_siblings():
if item.name == 'strong':
break
text_before = item.previous_sibling
if isinstance(text_before, NavigableString):
texts.append(text_before)
return ' '.join(texts)
并为不同的部分调用它:
print get_section_text('Adresa:')
print get_section_text('Telefón:')
print get_section_text('Fax:')
它会打印:
Obecný úrad Nána Madáchova 32 943 60 Nána
036/759 70 06
036/7597 007
对于不存在的部分:
print get_section_text('ILLEGAL SECTION')
它引发了一个异常
ValueError: Section not found
关于python - 获取由标签分隔的文本/BS4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25834191/