【问题标题】:Beautifulsoup can't find tag by textBeautifulsoup 无法通过文本找到标签
【发布时间】:2015-05-12 16:25:39
【问题描述】:

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

可能出了什么问题?

【问题讨论】:

  • 您是否可以通过搜索spandate 类找到文本?
  • @AnthonyForloney 是的,我是 :) 这很奇怪。这是 findAll/span/class=date 的输出:[Kontaktní osoba: Jozef, Ulice, č。 p.: M.M 3, Město: Bratis, Okres: 布拉迪斯克拉吉:布拉迪斯PSČ:84147 , 电话:+4205545575, 电子邮件:
    print(soup.find('span',{"class":"date"})) 呢?
  • @PadraicCunningham 它返回满足此条件的第一个跨度。它有效,所以我不知道是什么问题。

标签: python web-scraping beautifulsoup


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签