I have been trying to download data from a website and then save it to a csv file. The problem is: I cannot save it in a proper way to read it or to import into a database.
Here is my code:
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")
And the output on the CSV file:
M;a;y; ;3;1;,; ;2;0;1;7
1;.;1;2;1;8
1;.;1;1;7;2
1;.;1;2;2;0
....
What I need:
May 31, 2017;1.1218;1.1172;1.1220;1.1165;0.30%
If you check the website, everything is in a table and I need it similar in csv. What should I change to make it work?