_bs.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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 state date race horse')
  20. def get_today_row(this_text, this_row):
  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. :param this_row:
  27. :return RaceDay this_race_day:
  28. """
  29. this_soup = BeautifulSoup(this_text, 'html.parser')
  30. rows = this_soup.select('tr.rows')
  31. # print('len(rows) {}'.format(len(rows)))
  32. all_race_days = []
  33. days_to_check = [this_row]
  34. if this_row == -1:
  35. days_to_check = range(len(rows))
  36. for day in days_to_check:
  37. my_row = rows[day]
  38. cells = my_row.select('td')
  39. i = 0
  40. states = ('NSW', 'VIC', 'QLD', 'WA', 'SA', 'TAS', 'ACT', 'NT')
  41. day = 'Unknown'
  42. for cell in cells:
  43. if i == 0:
  44. # First cell contains date information
  45. day = cell.find('span').getText()
  46. # print("date: {}".format(day))
  47. i += 1
  48. continue
  49. venue_text = cell.find('p').getText().strip()
  50. if len(venue_text) > 0:
  51. # Cell is not empty
  52. # print(venue_text)
  53. this_a = cell.findAll('a') # .get('href')
  54. for a in this_a:
  55. # There may be several links in a cell (which represents a state)
  56. venue_name = a.getText().strip()
  57. this_venue = Venue(states[i - 1], venue_name)
  58. date_string = day
  59. this_url = a.get('href')
  60. if this_url:
  61. # Create the Scratchings URL by substitution
  62. scratchings_url = re.sub(r"/(.*)\.aspx", 'Scratchings.aspx', this_url)
  63. scratchings_url = base_url + scratchings_url
  64. calculated_date = model.convert_to_date(date_string)
  65. this_race_day = RaceDayShort(this_venue.state, this_venue.name, date_string,
  66. calculated_date.strftime('%Y-%m-%d'), scratchings_url)
  67. all_race_days.append(this_race_day)
  68. i += 1
  69. return all_race_days
  70. def get_meta_data(this_data, this_venue):
  71. """
  72. Meta data is on the top-right of the Scratchings page. It contains a date and time for
  73. the latest update as well as the closing of reporting of Scratchings.
  74. This function scrapes both dateTimes and converts to unixtime (which is timezone unaware)
  75. The RaceDay namedTuple is accordingly extended.
  76. :param this_data:
  77. :param this_venue:
  78. :return:
  79. """
  80. this_soup = BeautifulSoup(this_data, 'html.parser')
  81. early = this_soup.select('div.large')
  82. # if early:
  83. # print(early.get_text())
  84. if early and 'not currently available' in early.get_text():
  85. # print(early.get_text())
  86. return
  87. try:
  88. this_meta_data = this_soup.select('div.race-venue-bottom')[0].select('div.col2')[0]
  89. except IndexError:
  90. return
  91. last_published_regex = re.compile('Scratchings Last Published: (.+? AEST)')
  92. close_regex = re.compile('Scratching close: (.+? AEST)')
  93. # The times tuple is filled with a dateTime string then a unixtime (seconds since 1970)
  94. times = ['', 0, '', 0]
  95. time_format = '%a %d-%b-%y %I:%M%p'
  96. aest = timezone('Australia/Brisbane')
  97. if this_meta_data:
  98. this_meta_data = this_meta_data.getText()
  99. match = last_published_regex.search(this_meta_data)
  100. if match:
  101. # print(this_venue.name)
  102. # pprint(match)
  103. times[0] = match.group(1)[:-5]
  104. # times[0] = 'Thu 20-Jun-19 7:42AM'
  105. l_time = datetime.datetime.strptime(times[0], time_format)
  106. # print(aest.localize(l_time))
  107. times[1] = model.convert_to_unixtime(aest.localize(l_time))
  108. # print(times[1])
  109. match = close_regex.search(this_meta_data)
  110. if match:
  111. times[2] = match.group(1)[:-5]
  112. l_time = datetime.datetime.strptime(times[2], time_format)
  113. times[3] = model.convert_to_unixtime(aest.localize(l_time))
  114. # The RaceDAy namedTuple is created and filled
  115. race_day = RaceDay(this_venue.state, this_venue.name, this_venue.date_string,
  116. this_venue.date, this_venue.scratchings_url,
  117. times[0], times[1], times[2], times[3])
  118. return race_day
  119. def scrape_scratchings(div, this_venue):
  120. old_race = 0
  121. race = 0
  122. scraped_scratchings = []
  123. for text in div.stripped_strings:
  124. if text[:5] == 'Race ':
  125. match = re.search('^Race ([0-9]+):$', text)
  126. if match:
  127. try:
  128. race = int(match.group(1))
  129. except ValueError:
  130. # This will happily fail in the next assert
  131. race = 0
  132. assert race > old_race, 'race {} ! > old_race {}'.format(race, old_race)
  133. old_race = race
  134. continue
  135. if text[0] == '(':
  136. continue
  137. if len(text) > 0:
  138. if text[0:10] == 'There are ':
  139. continue
  140. try:
  141. int(text[0])
  142. except ValueError:
  143. print('First character in line: {}'.format(text[0]))
  144. print('The start of the offending line is: {}'.format(text[0:10]))
  145. continue
  146. text = re.sub(r'e\s+', ' ', text)
  147. text = re.sub(r'\s+', ' ', text) # Kills tabs between number and name of horse
  148. temp_list = Scratching(this_venue.name, this_venue.state, this_venue.date, race, text)
  149. scraped_scratchings.append(temp_list)
  150. return scraped_scratchings
  151. def process_scratchings(this_data, this_venue):
  152. this_soup = BeautifulSoup(this_data, 'html.parser')
  153. try:
  154. this_scr = this_soup.select('div.scratchings')[0]
  155. except IndexError:
  156. return
  157. scratchings_count = this_scr.select('table')[0].select('tr')[2].select('td')[3].getText()
  158. # print('{}: scratchings_count {}'.format(this_venue.name, scratchings_count))
  159. header = this_scr.findAll('h3', text=re.compile('Scratchings'))[0]
  160. div = header.findNext('table')
  161. scratchings = set()
  162. early_scratchings = scrape_scratchings(div, this_venue)
  163. scratchings.update(early_scratchings)
  164. header = this_scr.findAll('h3', text=re.compile('Late Scratchings'))[0]
  165. late_div = header.findNext('table')
  166. late_scratchings = scrape_scratchings(late_div, this_venue)
  167. # if this_venue.name == 'Corowa':
  168. # pprint(late_div)
  169. # pprint(late_scratchings)
  170. scratchings.update(late_scratchings)
  171. assert len(scratchings) == int(scratchings_count), 'len(scratchings) {} == scratchings_count {}'.format(
  172. len(scratchings), scratchings_count)
  173. # if len(scratchings) != int(scratchings_count):
  174. # print('len(scratchings) {} == scratchings_count {}'.format(
  175. # len(scratchings), scratchings_count))
  176. # pprint(scratchings)
  177. return scratchings