python - 获取由标签分隔的文本/BS4

标签 python html beautifulsoup html-parsing

如何从标签中获取文本,其中属性由
或标签分隔?例如,对于下面代码中的“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/

相关文章:

python - 在Python3中从字符串中抓取某些文本

python - 在 Jinja2 迭代中获取倒数第二个元素

html - HTML 中的 CSS 类引用

python - 使用 beautifulsoup 获取 HTML 中链接标签内的标题

python - 网页抓取谷歌财经

python - 无法在带有 Ubuntu 的 Python 中使用标准输入

javascript - 更改类以将其添加到链接

html - 单击时导航中的元素会稍微分开

python - 如何填写 html 表单并从网站上抓取?

python - 通过 linux ping 并在 python 中获取输出