【问题标题】:How to find a span containing a particular word如何找到包含特定单词的跨度
【发布时间】:2021-04-23 02:21:54
【问题描述】:

我正在使用 BeautifulSoup 来解析网页。现在我想从跨度读取索引值31811.75

<span>Underlying Index: <b style="font-size:1.2em;">BANKNIFTY 31811.75</b> </span>

不幸的是,跨度缺少任何其他标识,例如class。我遵循了on a similar question 中提到的解决方案,但我似乎没有得到全文:

>>> print(soup.body(text=re.compile('Underlying')))
['Underlying Index: ']

我希望使用关键字Underlying 来提取存在于跨度中的文本。我该怎么做?

【问题讨论】:

    标签: python-3.x beautifulsoup


    【解决方案1】:

    创建了一个合成 HTML 文档,其中包含我们不想找到的 span。使用re.findall()从找到的文本中提取小数

    from bs4 import BeautifulSoup
    import re
    html = """
    <html><body>
    <span>unwanted</span>
    <span>Underlying Index: <b style="font-size:1.2em;">BANKNIFTY 31811.75</b> </span>
    </html></body>
    """
    
    soup = BeautifulSoup(html)
    index = re.findall("\d+\.\d+", soup.find(lambda tag:tag.name=="span" and "Underlying" in tag.text).text )
    index[0] if len(index)==1 else None # re.findall() returns a list,  take first located decimal.  Could default to 0.0 instead of None
    

    输出

    '31811.75'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 2015-04-01
      • 1970-01-01
      相关资源
      最近更新 更多