_bs.py 6.8 KB

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