【问题标题】:Web scraping coinmarketcap.com with Python (requests & BeautifulSoup)使用 Python 抓取 coinmarketcap.com 的网页(请求和 BeautifulSoup)
【发布时间】:2018-03-09 11:15:24
【问题描述】:

我想用来自 coinmarketcap.com 的硬币建立一个列表。 每个元素都应该是一个元组。

类似:

coins = [('btc',8500,'+0.5%','+1.2%', '-1%'), ...]

我无法获得百分比: 信息在td 中是这样的:

<td class="no-wrap percent-change   text-right positive_change" data-timespan="1h" data-percentusd="0.99" data-symbol="BTC" data-sort="0.991515">0.99%</td>

如何从上面获取 0.99% 的值?我实际上需要来自 td 的 data-percentageusd,但我不知道那是什么。

我的测试脚本是这样的:

import requests
from bs4 import BeautifulSoup

url = 'https://coinmarketcap.com/all/views/all/'
page = requests.get(url)
soup = BeautifulSoup(page.content,'html.parser')

name = soup.find_all('a', class_='currency-name-container')
price = soup.find_all('a', class_='price')
print(name)
print(price)
#how can percentage modification for 1h, 24h, 7d?
#delta_h = soup.find_all('td', ???)

【问题讨论】:

标签: python web web-scraping beautifulsoup python-requests


【解决方案1】:

您可以遍历表的行以获取每种货币的数据并将其存储在一个元组中,然后将其添加到列表中。

r = requests.get('https://coinmarketcap.com/all/views/all/')
soup = BeautifulSoup(r.text, 'lxml')

data = []
table = soup.find('table', id='currencies-all')
for row in table.find_all('tr'):
    try:
        symbol = row.find('td', class_='text-left col-symbol').text
        price = row.find('a', class_='price').text
        time_1h = row.find('td', {'data-timespan': '1h'}).text
        time_24h = row.find('td', {'data-timespan': '24h'}).text
        time_7d = row.find('td', {'data-timespan': '7d'}).text
    except AttributeError:
        continue

    data.append((symbol, price, time_1h, time_24h, time_7d))

for item in data:
    print(item)

部分输出:

('BTC', '$8805.46', '0.88%', '-12.30%', '-19.95%')
('ETH', '$677.45', '0.98%', '-11.54%', '-21.66%')
('XRP', '$0.780113', '0.62%', '-10.63%', '-14.42%')
('BCH', '$970.70', '1.01%', '-11.33%', '-23.89%')
('LTC', '$166.70', '0.74%', '-10.06%', '-19.56%')
('NEO', '$83.55', '0.24%', '-16.29%', '-33.39%')
('XLM', '$0.286741', '1.13%', '-13.23%', '-11.84%')
('ADA', '$0.200449', '0.63%', '-16.92%', '-31.43%')
('XMR', '$256.92', '0.63%', '-19.98%', '-19.46%')

由于表中某些货币的数据缺失,代码将为.text 引发AttributeError。为了跳过这些货币,我使用了 try-except。

【讨论】:

    猜你喜欢
    • 2020-04-20
    • 2016-02-21
    • 2020-07-24
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    相关资源
    最近更新 更多