【问题标题】:How to extract content inside a label using beautiful soup in Python?如何在 Python 中使用美丽的汤提取标签内的内容?
【发布时间】:2020-06-12 08:55:09
【问题描述】:

我使用以下代码使用美丽的汤提取了 div 类:

soup = soup.find('div',id="capatcha")

我想提取标签类中的内容——哪一个更大的文本。 请注意, id="j_idt40" 总是在变化。 我试图通过将其转换为字符串来拆分它,但这没有帮助:(

<div class="ui-outputpanel ui-widget inline-section bottom-space-2" id="capatcha"><label class="ui-outputlabel ui-widget label-captcha" id="j_idt40">Which one is greater      3   ,   8</label></div>

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:

    您可以使用.text 属性获取&lt;div&gt; 标记的文本。要获取特定数字,您可以使用re 模块。

    例如:

    txt = '''<div class="ui-outputpanel ui-widget inline-section bottom-space-2" id="capatcha"><label class="ui-outputlabel ui-widget label-captcha" id="j_idt40">Which one is greater      3   ,   8</label></div>'''
    
    import re
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(txt, 'html.parser')
    
    text = soup.select_one('#capatcha').text
    numbers = list(map(int, re.findall(r'\d+', text)))
    
    print(text)
    print(numbers)
    

    打印:

    Which one is greater      3   ,   8
    [3, 8]
    

    【讨论】:

      猜你喜欢
      • 2015-12-25
      • 2016-03-22
      • 2018-07-18
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 2020-03-17
      相关资源
      最近更新 更多