![](/img/trans.png)
[英]Using beautiful soup to get values from cells in rows in tables shows {{row.value}} as a result
[英]Using beautiful soup to get values from cells in rows in tables
使用來自http://coinmarketcap.com/的HTML我試圖創建一個包含HTML值的python字典,例如:
{比特幣:{Market_cap:'$ 11,247,442,728',成交量:'$ 64,668,900'},以太坊:....等}
我怎么也不熟悉HTML的結構。 對於某些市場上限,單元格(td)鏈接到數據,即:
<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>
這是我正在使用的代碼:
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
這會產生大量空白區域和缺少數據的結果。
對於每一行,我如何獲得硬幣的名稱? 對於每個單元格,如何訪問每個值? 無論是link()還是常規值
編輯:
通過將for循環更改為:
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%
但是我很清楚每個單元格的類名,即
id: bitcoin
marketcap: 11,254,003,178
etc......
你快到了。 而不是使用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')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.