_bs.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. from bs4 import BeautifulSoup
  2. import re
  3. import datetime
  4. from pytz import timezone
  5. import model
  6. import collections
  7. from string import capwords
  8. # import pytz
  9. # from pprint import pprint
  10. """
  11. This module contains custom methods based on bs4.beautifulsoup to analyze data
  12. """
  13. base_url = 'https://racingaustralia.horse/FreeFields/'
  14. Venue = collections.namedtuple('Venue', 'state, name')
  15. RaceDayShort = collections.namedtuple('RaceDayShort', Venue._fields + ('date_string', 'date', 'scratchings_url'))
  16. # noinspection PyProtectedMember,PyUnresolvedReferences
  17. RaceDay = collections.namedtuple('RaceDay', RaceDayShort._fields + (
  18. 'scratchings_latest_datetime', 'scratchings_latest_unixtime',
  19. 'scratchings_close_datetime', 'scratchings_close_unixtime'))
  20. RawScratching = collections.namedtuple('RawScratching', 'venue state date race horse_no horse_display_name')
  21. Scratching = collections.namedtuple('Scratching', 'venue state date race time utc horse_no horse_display_name torn')
  22. def get_today_row(this_text, this_row):
  23. """
  24. Traverses the main table on the front page of https://racingaustralia.horse.
  25. This function scrapes Venue information and race day information.
  26. Unfortunately there is no clever way to split this function into two parts.
  27. :param this_text:
  28. :param this_row:
  29. :return RaceDay this_race_day:
  30. """
  31. this_soup = BeautifulSoup(this_text, 'html.parser')
  32. rows = this_soup.select('tr.rows')
  33. # print('len(rows) {}'.format(len(rows)))
  34. all_race_days = []
  35. days_to_check = [this_row]
  36. if this_row == -1:
  37. days_to_check = range(len(rows))
  38. for day in days_to_check:
  39. my_row = rows[day]
  40. cells = my_row.select('td')
  41. i = 0
  42. states = ('NSW', 'VIC', 'QLD', 'WA', 'SA', 'TAS', 'ACT', 'NT')
  43. day = 'Unknown'
  44. for cell in cells:
  45. if i == 0:
  46. # First cell contains date information
  47. day = cell.find('span').getText()
  48. # print("date: {}".format(day))
  49. i += 1
  50. continue
  51. venue_text = cell.find('p').getText().strip()
  52. if len(venue_text) > 0:
  53. # Cell is not empty
  54. # print(venue_text)
  55. this_a = cell.findAll('a') # .get('href')
  56. for a in this_a:
  57. # There may be several links in a cell (which represents a state)
  58. venue_name = a.getText().strip()
  59. this_venue = Venue(states[i - 1], venue_name)
  60. date_string = day
  61. this_url = a.get('href')
  62. if this_url:
  63. # Create the Scratchings URL by substitution
  64. scratchings_url = re.sub(r"/(.*)\.aspx", 'Scratchings.aspx', this_url)
  65. scratchings_url = base_url + scratchings_url
  66. calculated_date = model.convert_to_date(date_string)
  67. this_race_day = RaceDayShort(this_venue.state, this_venue.name, date_string,
  68. calculated_date, scratchings_url)
  69. all_race_days.append(this_race_day)
  70. i += 1
  71. return all_race_days
  72. def get_meta_data(this_data, this_venue):
  73. """
  74. Meta data is on the top-right of the Scratchings page. It contains a date and time for
  75. the latest update as well as the closing of reporting of Scratchings.
  76. This function scrapes both dateTimes and converts to unixtime (which is timezone unaware)
  77. The RaceDay namedTuple is accordingly extended.
  78. :param this_data:
  79. :param this_venue:
  80. :return:
  81. """
  82. this_soup = BeautifulSoup(this_data, 'html.parser')
  83. early = this_soup.select('div.large')
  84. # if early:
  85. # print(early.get_text())
  86. if early and 'not currently available' in early.get_text():
  87. # print(early.get_text())
  88. return
  89. try:
  90. this_meta_data = this_soup.select('div.race-venue-bottom')[0].select('div.col2')[0]
  91. except IndexError:
  92. return
  93. last_published_regex = re.compile('Scratchings Last Published: (.+? AEST)')
  94. close_regex = re.compile('Scratching close: (.+? AEST)')
  95. # The times tuple is filled with a dateTime string then a unixtime (seconds since 1970)
  96. times = ['', 0, '', 0]
  97. time_format = '%a %d-%b-%y %I:%M%p'
  98. aest = timezone('Australia/Brisbane')
  99. if this_meta_data:
  100. this_meta_data = this_meta_data.getText()
  101. match = last_published_regex.search(this_meta_data)
  102. if match:
  103. # print(this_venue.name)
  104. # pprint(match)
  105. times[0] = match.group(1)[:-5]
  106. # times[0] = 'Thu 20-Jun-19 7:42AM'
  107. l_time = datetime.datetime.strptime(times[0], time_format)
  108. # print(aest.localize(l_time))
  109. times[1] = model.convert_to_unixtime(aest.localize(l_time))
  110. # print(times[1])
  111. match = close_regex.search(this_meta_data)
  112. if match:
  113. times[2] = match.group(1)[:-5]
  114. l_time = datetime.datetime.strptime(times[2], time_format)
  115. times[3] = model.convert_to_unixtime(aest.localize(l_time))
  116. # The RaceDAy namedTuple is created and filled
  117. race_day = RaceDay(this_venue.state, this_venue.name, this_venue.date_string,
  118. this_venue.date, this_venue.scratchings_url,
  119. times[0], times[1], times[2], times[3])
  120. return race_day
  121. def scrape_scratchings(div, this_venue):
  122. old_race = 0
  123. race = 0
  124. scraped_scratchings = []
  125. for text in div.stripped_strings:
  126. if text[:5] == 'Race ':
  127. match = re.search('^Race ([0-9]+):$', text)
  128. if match:
  129. try:
  130. race = int(match.group(1))
  131. except ValueError:
  132. # This will happily fail in the next assert
  133. race = 0
  134. assert race > old_race, 'race {} ! > old_race {}'.format(race, old_race)
  135. old_race = race
  136. continue
  137. if text[0] == '(':
  138. continue
  139. if len(text) > 0:
  140. if text[0:10] == 'There are ':
  141. continue
  142. try:
  143. int(text[0])
  144. except ValueError:
  145. print('First character in line: {}'.format(text[0]))
  146. print('The start of the offending line is: {}'.format(text[0:10]))
  147. continue
  148. match = re.search(r'^(\d{1,2})e?\s+(.+)', text)
  149. no = 0
  150. name = ''
  151. if match:
  152. no = int(match.group(1))
  153. name = capwords(match.group(2))
  154. name = re.sub(r' Of ', ' of ', name)
  155. if name.endswith('(nz)'):
  156. name = name[:-len(' (nz)')]
  157. # text = re.sub(r'e\s+', ' ', text)
  158. # text = re.sub(r'\s+', ' ', text) # Kills tabs between number and name of horse
  159. temp_list = RawScratching(this_venue.name, this_venue.state, this_venue.date, race, no, name)
  160. scraped_scratchings.append(temp_list)
  161. return scraped_scratchings
  162. def process_scratchings(this_data, this_venue):
  163. this_soup = BeautifulSoup(this_data, 'html.parser')
  164. try:
  165. this_scr = this_soup.select('div.scratchings')[0]
  166. except IndexError:
  167. return
  168. scratchings_count = this_scr.select('table')[0].select('tr')[2].select('td')[3].getText()
  169. # print('{}: scratchings_count {}'.format(this_venue.name, scratchings_count))
  170. header = this_scr.findAll('h3', text=re.compile('Scratchings'))[0]
  171. div = header.findNext('table')
  172. scratchings = set()
  173. early_scratchings = scrape_scratchings(div, this_venue)
  174. scratchings.update(early_scratchings)
  175. # print('len(scratchings): {}'.format(len(scratchings)))
  176. header = this_scr.findAll('h3', text=re.compile('Late Scratchings'))[0]
  177. late_div = header.findNext('table')
  178. late_scratchings = scrape_scratchings(late_div, this_venue)
  179. # if this_venue.name == 'Corowa':
  180. # pprint(late_div)
  181. # pprint(late_scratchings)
  182. scratchings.update(late_scratchings)
  183. # print('len(scratchings): {}'.format(len(scratchings)))
  184. assert len(scratchings) == int(scratchings_count), 'len(scratchings) {} == scratchings_count {}'.format(
  185. len(scratchings), scratchings_count)
  186. # if len(scratchings) != int(scratchings_count):
  187. # print('len(scratchings) {} == scratchings_count {}'.format(
  188. # len(scratchings), scratchings_count))
  189. # pprint(scratchings)
  190. return scratchings
  191. def get_racenet_json(html):
  192. this_soup = BeautifulSoup(html, 'html.parser')
  193. pattern = re.compile(r'window\.initialReduxState = (.*)')
  194. script = this_soup.find('script', text=pattern)
  195. json = '{}'
  196. if script:
  197. # print('script')
  198. match = pattern.search(script.text)
  199. if match:
  200. # print('match')
  201. json = match.group(1)
  202. else:
  203. print('Failing in {}'.format("'match'"))
  204. else:
  205. print('Failing in {}'.format("'script'"))
  206. # pprint(json)
  207. return json