【问题标题】:how to obtain class contents in html using beautifulsoup?如何使用beautifulsoup 获取html 中的类内容?
【发布时间】:2015-03-11 03:12:21
【问题描述】:

这是我希望使用的 html 代码:

<section id='price'>

<div class="row">
    <h4 class='col-sm-4'>Market Cap: <b><i class="fa fa-inr"></i> 10.64 Crores</b></h4>
    <h4 class='col-sm-4'>Current Price: <b><i class="fa fa-inr"></i> 35.35</b></h4>
    <h4 class='col-sm-4'>Book Value: <b><i class="fa fa-inr"></i> 53.52</b></h4>
</div>

我的问题是如何从“class='col-sm-4'”中获取市值、当前价格、账面价值。

因为如果我尝试:

print soup.row.col-sm-4.fa.fa-inr

它不起作用。我对 python 和网络抓取有点陌生所以请耐心地走过这个过程。提前致谢。

【问题讨论】:

    标签: python html web-scraping beautifulsoup html-parsing


    【解决方案1】:

    您可以通过文本找到标签并获取next_element

    from bs4 import BeautifulSoup
    
    data = """
    <div class="row">
            <h4 class='col-sm-4'>Market Cap: <b><i class="fa fa-inr"></i> 10.64 Crores</b></h4>
            <h4 class='col-sm-4'>Current Price: <b><i class="fa fa-inr"></i> 35.35</b></h4>
            <h4 class='col-sm-4'>Book Value: <b><i class="fa fa-inr"></i> 53.52</b></h4>
        </div>
    """
    soup = BeautifulSoup(data)
    
    titles = ['Market Cap', 'Current Price', 'Book Value']
    for title in titles:
        print soup.find(text=lambda x: x.startswith(title)).next_element.text
    

    打印:

    10.64 Crores
    35.35
    53.52
    

    要获取浮点值,你可以简单地按空格分割并获取第一个元素:

    price = soup.find(text=lambda x: x.startswith(title)).strip().split()[0]
    print float(price)
    

    您也可以通过CSS Selector 获取它们:

    for item in soup.select('section#price div.row h4.col-sm-4 b'):
        print item.text
    

    【讨论】:

    • 您能否解释一下如何具体获取代码的市场价值..for item in soup.select("section#price div.row h4.col-sm-4 b i.fa.fa-inr"): print item.text 不起作用并产生空白输出
    • @Bharat 是的,但我没有建议您使用您正在使用的选择器。使用section#price div.row h4.col-sm-4 b
    • 您的代码生成的输出包含所有值,即。市值,当前价格和账面价值,但我只需要单独的市值。这怎么可能?
    • @Bharat 明白了,当然,只需使用 soup.select('section#price div.row h4.col-sm-4 b')[0].text
    【解决方案2】:

    试试这样:

    >>> for x in soup.find_all("div","row"):
    ...     print x.text
    ... 
    
    Market Cap:  10.64 Crores
    Current Price:  35.35
    Book Value:  53.52
    

    【讨论】:

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