【问题标题】:How to extract exact information by span class using Beautiful Soup如何使用 Beautiful Soup 按跨度类提取准确信息
【发布时间】:2021-02-15 11:51:09
【问题描述】:

这是我的价格监控代码的代码和输出:

soup = BeautifulSoup(page.content, 'html.parser')

title = soup.find(id="result_0_name").get_text()
price = soup.find("span", class_ = "normal_price")
#converted_price = price[0:3]

print(price.get_text())
print(title.strip())

输出如下

Starting at:
$0.70 USD
$0.67 USD

Operation Broken Fang Case

页面的html也是这样

<span class="market_table_value normal_price">Starting at:<br/>
<span class="normal_price" data-currency="1" data-price="69">$0.69 USD</span>
<span class="sale_price">$0.66 USD</span>
</span>

您可以看到没有 ID,所以我不能使用它,我只想显示“normal_price”而不是该范围内的其他数据。有什么想法吗?

【问题讨论】:

    标签: python html beautifulsoup pycharm


    【解决方案1】:

    只需使跨度的选择更具体,例如使用它是元素中的元素这一事实:

    soup.select_one('span > span.normal_price').get_text()
    

    示例

    from bs4 import BeautifulSoup
    
    html='''
    <span class="market_table_value normal_price">
                        Starting at:<br/>
    <span class="normal_price" data-currency="1" data-price="69">$0.69 USD</span>
    <span class="sale_price">$0.66 USD</span>
    </span>
    '''
    soup = BeautifulSoup(html,'html.parser')
    
    price = soup.select_one('span > span.normal_price').get_text()
    
    price
    

    输出

    $0.69 USD
    

    【讨论】:

      【解决方案2】:

      你也可以这样试试

      from bs4 import BeautifulSoup
      html ="""<span class="market_table_value normal_price">
                          Starting at:<br/>
      <span class="normal_price" data-currency="1" data-price="69">$0.69 USD</span>
      <span class="sale_price">$0.66 USD</span>
      </span>"""
      
      soup = BeautifulSoup(html, 'html.parser')
      
      using attribute
      price = soup.select_one('span[data-currency="1"]').get_text()
      exact attribute
      price = soup.select_one('span[data-currency^="1"]').get_text()
      
      print(price) #$0.69 USD
      

      【讨论】:

      • 是的,这行得通,我没有从类属性之外查看它。另外,我刚开始上大学,我对编码很安静,有没有可以参考的指南,可以帮助我理解不同的 API。非常感谢您的帮助
      • 你可以关注beautifulsoup文档crummy.com/software/BeautifulSoup/bs4/doc
      • 请点赞,接受这个/任何对你有用的答案
      猜你喜欢
      • 1970-01-01
      • 2022-12-05
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 2014-01-10
      • 2019-03-21
      • 2011-11-03
      相关资源
      最近更新 更多