我想通過python從這個鏈接下載excel檔案 https://www.tfex.co.th/tfex/historicalTrading.html?locale=en_US&symbol=S50Z21&decorator=excel&series=&page=4&locale=en_US&locale=en_US&periodView=A
這是我的代碼:
url = 'https://www.tfex.co.th/tfex/historicalTrading.html?locale=en_US&symbol=S50Z21&decorator=excel&series=&page=4&locale=en_US&periodView=A'
resp = requests.get(url)
with open('file.xls','wb') as f:
f.write(resp.content)
但 file.xls 是一個 html 文本檔案。file.xls 看起來像這樣。1
我試過添加標題
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
resp = requests.get(url, headers=headers)
但這沒有幫助。先感謝您。
uj5u.com熱心網友回復:
編輯:找到了一種使用熊貓的方法。
import pandas as pd
url = r'https://www.tfex.co.th/tfex/historicalTrading.html?locale=en_US&symbol=S50Z21&decorator=excel&series=&page=4&locale=en_US&periodView=A'
# read into HTML tables
tables = pd.read_html(url)
# merge HTML tables
merged = pd.concat(tables)
# Write tables to excel file
merged.to_excel("output.xlsx")
希望這可以幫助 :)
忽略下面,這是在編輯之前:
我知道這仍然存在問題,具體取決于您的下游應用程式。下面的代碼似乎仍然將其下載為 HTML 格式,但無論如何都可以在 excel 中打開這種格式。
import requests
url = r'https://www.tfex.co.th/tfex/historicalTrading.html?locale=en_US&symbol=S50Z21&decorator=excel&series=&page=4&locale=en_US&periodView=A'
r = requests.get(url, allow_redirects=False)
excel_url = r.url
open('out.xls', 'wb').write(r.content)
當我在 excel 中打開它時,我收到一條警告,然后單擊確定。
檔案截圖
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/442633.html
