【问题标题】:BeautifulSoup scraping Bitcoin Price issueBeautifulSoup 抓取比特币价格问题
【发布时间】:2017-12-11 19:01:07
【问题描述】:

我还是 python 新手,尤其是 BeautifulSoup。几天来,我一直在阅读这些东西,并玩弄了一堆不同的代码并获得了混合结果。但是,在this 页面上是我想抓取的比特币价格。价格位于: <span class="text-large2" data-currency-value="">$16,569.40</span> 这意味着,我想让我的脚本只打印值所在的那一行。我当前的代码打印了整个页面,看起来不太好,因为它打印了很多数据。有人可以帮忙改进我的代码吗?

import requests
from BeautifulSoup import BeautifulSoup

url = 'https://coinmarketcap.com/currencies/bitcoin/'
response = requests.get(url)
html = response.content

soup = BeautifulSoup(html)
div = soup.find('text-large2', attrs={'class': 'stripe'})

for row in soup.findAll('div'):
    for cell in row.findAll('tr'):
        print cell.text

这是我运行代码后得到的输出的一个片段。它看起来不太好,也不太可读。

#SourcePairVolume (24h)PriceVolume (%)Updated
1BitMEXBTC/USD$3,280,130,000$15930.0016.30%Recently
2BithumbBTC/KRW$2,200,380,000$17477.6010.94%Recently
3BitfinexBTC/USD$1,893,760,000$15677.009.41%Recently
4GDAXBTC/USD$1,057,230,000$16085.005.25%Recently
5bitFlyerBTC/JPY$636,896,000$17184.403.17%Recently
6CoinoneBTC/KRW$554,063,000$17803.502.75%Recently
7BitstampBTC/USD$385,450,000$15400.101.92%Recently
8GeminiBTC/USD$345,746,000$16151.001.72%Recently
9HitBTCBCH/BTC$305,554,000$15601.901.52%Recently

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    试试这个:

    import requests
    from BeautifulSoup import BeautifulSoup
    
    url = 'https://coinmarketcap.com/currencies/bitcoin/'
    response = requests.get(url)
    html = response.content
    
    soup = BeautifulSoup(html)
    div = soup.find("div", {"class" : "col-xs-6 col-sm-8 col-md-4 text-left" 
    }).find("span", {"class" : "text-large2"})
    
    for i in div:
        print i
    

    这将为我打印 16051.20。

    稍后编辑:如果你把上面的代码放在一个函数中并循环它,它会不断更新。我现在得到不同的值。

    【讨论】:

      【解决方案2】:

      这行得通。但是我认为您使用的是旧版本的 BeautifulSoup,请在命令提示符或 PowerShell 中尝试pip install bs4

      import requests
      from bs4 import BeautifulSoup
      
      url = 'https://coinmarketcap.com/currencies/bitcoin/'
      response = requests.get(url)
      html = response.text
      
      soup = BeautifulSoup(html, 'html.parser')
      
      value = soup.find('span', {'class': 'text-large2'})
      print(''.join(value.stripped_strings))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-28
        • 2022-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多