-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBetfair-Data-Scraper.py
113 lines (83 loc) · 3.25 KB
/
Betfair-Data-Scraper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import os
import requests
import pypyodbc as odbc #pip install pypyodbc
from urllib.parse import urljoin
from bs4 import BeautifulSoup #pip install beautifulsoup4
import pandas as pd #pip install pandas
# Add your settings
DRIVER = 'SQL Server'
SERVER_NAME = 'YOUR-SERVER-NAME'
DATABASE_NAME = 'BetfairData'
# Filters csv URL prefixes
# Currently looks for UK & IE 'place' files
# Can switch out to look for 'win' files
def matc(string):
if 'dwbfpricesukplace' in string or 'dwbfpricesireplace' in string:
return True
return False
url = 'https://promo.betfair.com/betfairsp/prices'
# Downloads csv files to the folder below and reimports to SQL Server
# Add your preferred location to download the csv
folder_location = r'C:\betfairdata'
if not os.path.exists(folder_location):os.mkdir(folder_location)
response = requests.get(url)
soup= BeautifulSoup(response.text, "html.parser")
def connection_string(driver, server_name, database_name):
conn_string = f"""
DRIVER={{{driver}}};
SERVER={server_name};
DATABASE={database_name};
Trust_Connection=yes;
"""
return conn_string
try:
conn = odbc.connect(connection_string(DRIVER, SERVER_NAME, DATABASE_NAME))
except odbc.DatabaseError as e:
print("Database error")
print(str(e.value[1]))
except odbc.Error as e:
print("Connection Error:")
print(str(e.value[1]))
cursor = conn.cursor()
# Include your SQL tablename
sql_insert ='''
INSERT INTO PlaceData
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
'''
# Dates are converted to int. eg 05-01-2010converts to 20100105
Date = input("Enter the Start DATE (DD-MM-YYYY) : ") #Start Date
Date = "".join(Date.split('-'))
Date = int(Date[4:] + Date[2:4] + Date[:2])
EndDate = input("Enter End DATE (DD-MM-YYYY) : ")
EndDate = "".join(EndDate.split('-')) #End Date
EndDate = int(EndDate[4:] + EndDate[2:4] + EndDate[:2])
for link in soup.select("a[href$='.csv']"):
# Fdate is extracted from the name of the csv file
Fdate = str(link['href'])[-12:-4]
Fdate = "".join(Fdate.split('-'))
Fdate = int(Fdate[4:] + Fdate[2:4] + Fdate[:2])
# Checking the condition Condition
if matc(link['href']) and Fdate <= EndDate and Fdate >= Date: #Between StartDate and EndDate
filename = os.path.join(folder_location,link['href'].split('/')[-1])
with open(filename, 'wb') as f:
f.write(requests.get(urljoin(url,link['href'])).content)
df = pd.read_csv(filename)
rc = df.shape[0]
for i in range(rc):
df['EVENT_DT'].iloc[i] = df['EVENT_DT'].iloc[i] + ":00"
df['EVENT_DT'] = pd.to_datetime(df['EVENT_DT']).dt.strftime('%Y-%m-%d %H:%M:%S')
df.fillna(0, inplace=True)
records = df.values.tolist()
try:
cursor.executemany(sql_insert, records)
cursor.commit();
except Exception as e:
cursor.rollback()
print(str(e))
finally:
print("Done")
# Cleans temporarily downloaded CSVs
os.remove(filename)
print("ALL FILES TRANSFERED")
cursor.close()
conn.close()