Beautifulsoup 无法按文本找到标签

Beautifulsoup can't find tag by text

Beautifulsoup突然找不到标签了

我有一个 html,其中出现了这个标签:

<span class="date">Telefon: <b>+421 902 808 344</b></span>

BS4 找不到这个标签:

telephone = soup.find('span',{'text':re.compile('.*Telefon.*')})
print telephone

>>> None

我试过很多方法,比如

find('span',text='Telefon: ')find('span', text=re.compile('Telefon: .*')

但没有任何效果。我已经尝试将 html.parser 更改为 lxml

可能有什么问题?

BeautifulSoup 将字符串 Telefon: 视为 span 标签内的 bs4.element.NavigableString。所以你可以用

找到它
import bs4
import re

soup = bs4.BeautifulSoup('<span class="date">Telefon: <b>+421 902 808 344</b></span>')
for span in soup.find_all('span', {'class':"date"}):
    if span.find(text=re.compile('Telefon:')):
        for text in span.stripped_strings:
            print(text)
# Telefon:
# +421 902 808 344

或者,您可以直接使用 lxml:

import lxml.html as LH

root = LH.fromstring('<span class="date">Telefon: <b>+421 902 808 344</b></span>')

for span in root.xpath('//span[@class="date" and contains(text(), "Telefon:")]'):
    print(span.text_content())
    # Telefon: +421 902 808 344