我一直在嘗試從網站下載數據,然後將其保存到csv文件。問題是:我無法以正確的方式將其讀取或導入到數據庫中。Python:將數據從BeautifulSoup保存到CSV
這裏是我的代碼:
import csv
import requests
from bs4 import BeautifulSoup
def getData(url_to_scrap='https://www.investing.com/currencies/eur-usd-historical-data', file=None, save_file="Name.csv"):
if url_to_scrap is not None:
header = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
r = requests.get(url_to_scrap, headers=header)
data = BeautifulSoup(r.content, 'html.parser')
else:
data = BeautifulSoup(open(file, encoding='utf8'), 'html.parser')
table = data.find(id='curr_table')
table = table.find_all('td')
row_data = []
for row in table:
row_data.append(row.get_text('data-real-value'))
with open(save_file, 'w') as save:
for row in row_data:
writer = csv.writer(save, delimiter=';')
writer.writerow(row)
getData(save_file="EUR USD Historical Data.csv")
而且CSV文件輸出:
M;a;y; ;3;1;,; ;2;0;1;7
1;.;1;2;1;8
1;.;1;1;7;2
1;.;1;2;2;0
....
我需要什麼:
May 31, 2017;1.1218;1.1172;1.1220;1.1165;0.30%
如果您檢查網站,一切都在一個表中,我需要它類似於csv。 我應該改變什麼才能使它工作?
thank you for your answer,it made the script better,but now need to remove the extra blank lines in the csv。我只是把''open(save_file,'wb')'改成''打開(save_file,'w')'**。現在,我怎樣才能刪除多餘的空行?編輯:** @ njoosse **只是使用鏈接來閱讀它,並使用'lineterminator ='\ n'' –
@VascoFerreira嗯爲什麼你把wb設回b?我建議你可以按照建議使用'wb'來移除多餘的換行符。 (見[這裏](https://stackoverflow.com/questions/23835866/many-tutorials-on-writing-csv-files-have-the-mode-set-to-wb-why)) – lukeA
@VascoFerreira So lineterminator會是wb的替代品嗎?很高興知道。如果你的問題解決了,你可以選擇一個答案標記爲已解決。 – lukeA