【发布时间】:2021-03-14 00:44:34
【问题描述】:
我正在抓取 HTML 并将数据存储在 pandas 数据框中。我需要一个循环,因为 html 中的数据位于多个 url 中。我的第一个想法是创建与 url 一样多的数据帧,创建许多变量,但我读过这是一个坏主意。我读过的解决方案是创建一个字典,但我不知道如何使用数据帧来做到这一点。我只想要一个最终数据帧,其中包含从第一个数据帧的第一行到最后一个数据帧的最后一行的信息。
这是我目前的代码
# To simulate I am a browser and send request to get the body of the response.
header = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
"X-Requested-With": "XMLHttpRequest"
}
# Coingecko containes 100 coins per page
uncomplete_URL = "https://www.coingecko.com/en?page="
for page in range (1,100): # Because I only want to analise the first 1000 coins
complete_URL = uncomplete_URL + str(page)
# To request info and then populate a pandas dataframe
r = requests.get(complete_URL, headers=header)
dfs = pd.read_html(r.text)
df = pd.concat(df) # EDIT I forgot this line
tmp_df.head()
大部分代码取自here
【问题讨论】:
-
我会将数据帧存储在一个列表中,然后在其中执行
pd.concat(dfs)。