I am trying to scrape historical data from a table in coinmarketcap. However, the code that I run gives back “no data.” I thought it would be fairly easy, but not sure what I am missing.
JavaScript
x
12
12
1
url = "https://coinmarketcap.com/currencies/bitcoin/historical-data/"
2
3
data = requests.get(url)
4
5
bs=BeautifulSoup(data.text, "lxml")
6
table_body=bs.find('tbody')
7
rows = table_body.find_all('tr')
8
for row in rows:
9
cols=row.find_all('td')
10
cols=[x.text.strip() for x in cols]
11
print(cols)
12
Output:
JavaScript
1
5
1
C:UsersEjeranaconda3envspythonProjectpython.exe C:/Users/Ejer/PycharmProjects/pythonProject/CloudSQL_test.py
2
['No Data']
3
4
Process finished with exit code 0
5
Advertisement
Answer
You don’t need to scrape the data, you can get
request it:
JavaScript
1
25
25
1
import time
2
import requests
3
4
5
def get_timestamp(datetime: str):
6
return int(time.mktime(time.strptime(datetime, '%Y-%m-%d %H:%M:%S')))
7
8
9
def get_btc_quotes(start_date: str, end_date: str):
10
start = get_timestamp(start_date)
11
end = get_timestamp(end_date)
12
url = f'https://web-api.coinmarketcap.com/v1/cryptocurrency/ohlcv/historical?id=1&convert=USD&time_start={start}&time_end={end}'
13
return requests.get(url).json()
14
15
16
data = get_btc_quotes(start_date='2020-12-01 00:00:00',
17
end_date='2020-12-10 00:00:00')
18
19
import pandas as pd
20
# making A LOT of assumptions here, hopefully the keys don't change in the future
21
data_flat = [quote['quote']['USD'] for quote in data['data']['quotes']]
22
df = pd.DataFrame(data_flat)
23
24
print(df)
25
Output:
JavaScript
1
11
11
1
open high low close volume market_cap timestamp
2
0 18801.743593 19308.330663 18347.717838 19201.091157 3.738770e+10 3.563810e+11 2020-12-02T23:59:59.999Z
3
1 19205.925404 19566.191884 18925.784434 19445.398480 3.193032e+10 3.609339e+11 2020-12-03T23:59:59.999Z
4
2 19446.966422 19511.404714 18697.192914 18699.765613 3.387239e+10 3.471114e+11 2020-12-04T23:59:59.999Z
5
3 18698.385279 19160.449265 18590.193675 19154.231131 2.724246e+10 3.555639e+11 2020-12-05T23:59:59.999Z
6
4 19154.180593 19390.499895 18897.894072 19345.120959 2.529378e+10 3.591235e+11 2020-12-06T23:59:59.999Z
7
5 19343.128798 19411.827676 18931.142919 19191.631287 2.689636e+10 3.562932e+11 2020-12-07T23:59:59.999Z
8
6 19191.529463 19283.478339 18269.945444 18321.144916 3.169229e+10 3.401488e+11 2020-12-08T23:59:59.999Z
9
7 18320.884784 18626.292652 17935.547820 18553.915377 3.442037e+10 3.444865e+11 2020-12-09T23:59:59.999Z
10
8 18553.299728 18553.299728 17957.065213 18264.992107 2.554713e+10 3.391369e+11 2020-12-10T23:59:59.999Z
11