我對網路抓取非常陌生,我正在嘗試了解如何抓取該網站上的所有 zip 檔案和常規檔案。最終目標是抓取所有資料,我最初認為我可以使用 pd.read_html 并輸入每個鏈接的串列并回圈遍歷每個 zip 檔案。
我對網路抓取非常陌生,所以任何幫助都會非常有用,到目前為止我已經嘗試了一些示例,請參閱下面的代碼
import pandas as pd
pd.read_html("https://www.omie.es/en/file-access-list?parents[0]=/&parents[1]=Day-ahead Market&parents[2]=1. Prices&dir= Day-ahead market hourly prices in Spain&realdir=marginalpdbc",match="marginalpdbc_2017.zip")
所以這就是我希望輸出的樣子,除了每個 zip 檔案都需要是它自己的資料框才能使用/回圈。目前,它似乎正在做的只是下載 zip 檔案的所有名稱,而不是實際資料。
謝謝
uj5u.com熱心網友回復:
要打開 zipfile 并將那里的檔案讀取到資料框,您可以使用下一個示例:
import requests
import pandas as pd
from io import BytesIO
from zipfile import ZipFile
zip_url = "https://www.omie.es/es/file-download?parents[0]=marginalpdbc&filename=marginalpdbc_2017.zip"
dfs = []
with ZipFile(BytesIO(requests.get(zip_url).content)) as zf:
for file in zf.namelist():
df = pd.read_csv(
zf.open(file),
sep=";",
skiprows=1,
skipfooter=1,
engine="python",
header=None,
)
dfs.append(df)
final_df = pd.concat(dfs)
# print first 10 rows:
print(final_df.head(10).to_markdown(index=False))
印刷:
0 | 1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|---|
2017 | 1 | 1 | 1 | 58.82 | 58.82 | 楠 |
2017 | 1 | 1 | 2 | 58.23 | 58.23 | 楠 |
2017 | 1 | 1 | 3 | 51.95 | 51.95 | 楠 |
2017 | 1 | 1 | 4 | 47.27 | 47.27 | 楠 |
2017 | 1 | 1 | 5 | 46.9 | 45.49 | 楠 |
2017 | 1 | 1 | 6 | 46.6 | 44.5 | 楠 |
2017 | 1 | 1 | 7 | 46.25 | 44.5 | 楠 |
2017 | 1 | 1 | 8 | 46.1 | 44.72 | 楠 |
2017 | 1 | 1 | 9 | 46.1 | 44.22 | 楠 |
2017 | 1 | 1 | 10 | 45.13 | 45.13 | 楠 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/504699.html