【问题标题】:Extract Price - Beautiful Soup提取价格 - 美丽的汤
【发布时间】:2021-04-03 16:35:21
【问题描述】:

我正在尝试从 HTML 中提取第一个价格(inc £)

HTML:

<div class="grid-item__price"><div class="inc-vat"><p class="price">
<span class="smaller currency-symbol">£</span>
        179.99
        <span class="vat-text"> inc. vat</span> </p></div>
<div class="ex-vat"><p class="price"><span class="smaller currency-symbol">£</span> 149.99 <span class="vat-text">ex. vat</span> </p></div>
</div>

Python:

for prices in products.find_all("div", {"class": "grid-item__price"}):
   print(prices)

预期结果:

179.99 英镑

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    尝试调用.next_sibling 方法,因为预期的输出是£,后跟价格(下一个兄弟)。

    from bs4 import BeautifulSoup
    
    html = """<div class="grid-item__price"><div class="inc-vat"><p class="price">
    <span class="smaller currency-symbol">£</span>
            179.99
            <span class="vat-text"> inc. vat</span> </p></div>
    <div class="ex-vat"><p class="price"><span class="smaller currency-symbol">£</span> 149.99 <span class="vat-text">ex. vat</span> </p></div>
    </div>"""
    
    
    soup = BeautifulSoup(html, "html.parser")
    
    price_symbol = soup.find("span", class_="smaller currency-symbol")
    print(price_symbol.text, price_symbol.next_sibling.strip())
    

    输出:

    £ 179.99
    

    【讨论】:

      猜你喜欢
      • 2015-05-08
      • 1970-01-01
      • 2020-01-19
      • 2016-09-11
      • 2018-09-13
      • 2021-05-24
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多