使用漂亮的汤从表格中的行中的单元格中获取值

时间:2016-11-08 04:35:21

标签: python html beautifulsoup

使用来自http://coinmarketcap.com/的HTML我试图创建一个包含HTML值的python字典,例如:

{比特币:{Market_cap:' $ 11,247,442,728',成交量:' $ 64,668,900'},ethereum:.... etc}

我怎么不熟悉HTML的结构。对于某些市场上限,单元格(td)链接到数据,即:

/foo

但是对于像交易量这样的单元格,该值是一个链接,因此格式不同,即:

<td class="no-wrap market-cap text-right" data-usd="11247442728.0" data-btc="15963828.0">

                      $11,247,442,728 

                </td> 

以下是我正在使用的代码:

<td class="no-wrap text-right"> 
                    <a href="/currencies/bitcoin/#markets" class="volume" data-usd="64668900.0" data-btc="91797.5">$64,668,900</a>
                </td>

这会产生大量空白区域和缺失数据的结果。

对于每一行,我如何获得硬币的名称? 对于每个单元格,如何访问每个值?它是链接()还是常规值

编辑:

将for循环更改为:

import requests 
from bs4 import BeautifulSoup as bs

request = requests.get('http://coinmarketcap.com/')

content = request.content

soup = bs(content, 'html.parser')  

table = soup.findChildren('table')[0]

rows = table.findChildren('tr')

for row in rows:
    cells = row.findChildren('td')
    for cell in cells:
        print cell.string

我能够获得我想要的数据,即:

for row in rows:
    cells = row.findChildren('td')
    for cell in cells:
        print cell.getText().strip().replace(" ", "")

但是,我很高兴为每个单元格命名,即

1
Bitcoin
$11,254,003,178
$704.95
15,964,212
BTC
$63,057,100
-0.11%

1 个答案:

答案 0 :(得分:1)

你快到了。不使用cell.string方法,而是使用cell.getText()。您可能需要对输出字符串进行一些清理以及删除多余的空白区域。我使用了正则表达式,但这里还有一些其他选项,具体取决于您的数据处于什么状态。我已经添加了一些Python 3兼容性以及打印功能。

from __future__ import print_function
import requests
import re

from bs4 import BeautifulSoup as bs

request = requests.get('http://coinmarketcap.com/')

content = request.content

soup = bs(content, 'html.parser')  

table = soup.findChildren('table')[0]

rows = table.findChildren('tr')

for row in rows:
    cells = row.findChildren('td')
    for cell in cells:
        cell_content = cell.getText()
        clean_content = re.sub( '\s+', ' ', cell_content).strip()
        print(clean_content)

表格标题存储在第一行,因此您可以像这样提取它们:

headers = [x.getText() for x in rows[0].findChildren('th')]