首页 > 解决方案 > 将 URL 中的日期添加为从 URL 列表中抓取 html 表形成的数据框中的列

问题描述

我需要从 xe.com 下载一组特定日期的货币汇率并将它们全部存储在一个表中,为此我编写了以下代码。

import pandas as pd

# list of dates to suffix to the url

dates = ['2020-01-31','2020-02-29','2020-03-31','2020-04-30','2020-05-31','2020-06-30','2020-07-31','2020-08-31','2020-09-30',
         '2020-10-31','2020-11-30','2020-12-31','2021-01-31','2021-02-28','2021-03-31','2021-04-30','2021-05-31','2021-06-30',
         '2021-07-01',#'2021-08-01','2021-09-01','2021-10-01','2021-11-01','2021-12-01'
         ]

# the constant part of the url

link = "https://www.xe.com/currencytables/?from=EUR&date="

# append each date from the list to the constant part of the url and then read each table of currency rates from each url and save them in a dataframe

df_list = []
urls = []
for date in dates:
    urls.append(link+date)
urls
for url in urls:
    df_list.append(pd.read_html(url)[0])
df_list

# concatenate all dataframes in one

rates_table = pd.concat(df_list, axis=0, ignore_index=True)
print(rates_table)

我不知道该怎么做是将每个特定 URL 的日期(或者换句话说,我的日期列表中的每个日期)作为列添加到每个相应的数据框,以便我知道连接时每种货币汇率的日期所有数据帧合二为一。我怎样才能做到这一点?

此外,我意识到使用 BeautifulSoup 可能更容易做到这一点,但我仍然没有研究过那个库,但我有兴趣看到这样的解决方案,以便我可以研究它。

谢谢

标签: pythonpandasdataframeweb-scraping

解决方案


IIUC,试试这个。

import pandas as pd

dates = [...]
link = "https://www.xe.com/currencytables/?from=EUR&date="

pd.concat(pd.read_html(link+d)[0].assign(Date=d) for d in dates)

Out[*]: 

    Currency               Name  Units per EUR  EUR per unit        Date
0        USD          US Dollar       1.108085      0.902458  2020-01-31
1        EUR               Euro       1.000000      1.000000  2020-01-31
2        GBP      British Pound       0.839899      1.190619  2020-01-31
3        INR       Indian Rupee      79.252091      0.012618  2020-01-31
4        AUD  Australian Dollar       1.654370      0.604460  2020-01-31
..       ...                ...            ...           ...         ...
166      ZMW     Zambian Kwacha      20.419028      0.048974  2020-04-30
167      CLF                CLF       0.033268     30.059155  2020-04-30
168      CNH                CNH       7.728135      0.129397  2020-04-30
169      MXV                MXV       4.119131      0.242770  2020-04-30
170      XBT            Bitcoin       0.000124   8062.078999  2020-04-30

推荐阅读