【问题标题】:Beautiful Soup Selector美丽的汤选择器
【发布时间】:2023-04-03 20:09:01
【问题描述】:

Beautiful Soup 非常新,并且一直坚持从以下代码中的“数据”获取两个值。理想情况下,我想选择 value1 (500) 作为“item1”,第二个值 (442) 作为“item2”。

<div  id="chart-1" class="charts-highchart"  data-chart="{&quot;chart&quot;:{&quot;type&quot;:&quot;pie&quot;,&quot;width&quot;:null,&quot;height&quot;:null,&quot;backgroundColor&quot;[&quot;Male&quot;,&quot;Female&quot;],&quot;data&quot;:[500,442]}],&quot;exporting&quot;pane&quot;:null}"
        style=""></div>

【问题讨论】:

    标签: python beautifulsoup css-selectors


    【解决方案1】:

    使用正则表达式 re 并使用以下 css 选择器。

    import re
    from bs4 import BeautifulSoup
    
    html='''<div  id="chart-1" class="charts-highchart"  data-chart="{&quot;chart&quot;:{&quot;type&quot;:&quot;pie&quot;,&quot;width&quot;:null,&quot;height&quot;:null,&quot;backgroundColor&quot;[&quot;Male&quot;,&quot;Female&quot;],&quot;data&quot;:[500,442]}],&quot;exporting&quot;pane&quot;:null}"
            style=""></div>'''
    soup=BeautifulSoup(html,'html.parser')
    data=soup.select_one('#chart-1[data-chart]')['data-chart']
    items=re.findall("(\d+)",data)
    for item in items:
        print(item)
    

    输出:

    500
    442
    

    如果你想在一个变量中赋值,使用这个。

    import re
    from bs4 import BeautifulSoup
    
    html='''<div  id="chart-1" class="charts-highchart"  data-chart="{&quot;chart&quot;:{&quot;type&quot;:&quot;pie&quot;,&quot;width&quot;:null,&quot;height&quot;:null,&quot;backgroundColor&quot;[&quot;Male&quot;,&quot;Female&quot;],&quot;data&quot;:[500,442]}],&quot;exporting&quot;pane&quot;:null}"
            style=""></div>'''
    soup=BeautifulSoup(html,'html.parser')
    data=soup.select_one('#chart-1[data-chart]')['data-chart']
    items=re.findall("(\d+)",data)
    item1=items[0]
    item2=items[-1]
    print(item1,item2)
    

    【讨论】:

      猜你喜欢
      • 2021-07-14
      • 2014-09-03
      • 2020-12-01
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多