_bs.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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, 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 == 0:
  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. this_race_day = RaceDayShort(this_venue.state, this_venue.name, date_string,
  65. '1970-01-01', scratchings_url)
  66. all_race_days.append(this_race_day)
  67. i += 1
  68. return all_race_days
  69. def get_meta_data(this_data, this_venue):
  70. """
  71. Meta data is on the top-right of the Scratchings page. It contains a date and time for
  72. the latest update as well as the closing of reporting of Scratchings.
  73. This function scrapes both dateTimes and converts to unixtime (which is timezone unaware)
  74. The RaceDay namedTuple is accordingly extended.
  75. :param this_data:
  76. :param this_venue:
  77. :return:
  78. """
  79. this_soup = BeautifulSoup(this_data, 'html.parser')
  80. early = this_soup.select('div.large')
  81. if early:
  82. print(early.get_text())
  83. if early and 'not currently available' in early.get_text():
  84. print(early.get_text())
  85. return
  86. try:
  87. this_meta_data = this_soup.select('div.race-venue-bottom')[0].select('div.col2')[0]
  88. except IndexError:
  89. return
  90. last_published_regex = re.compile('Scratchings Last Published: (.+? AEST)')
  91. close_regex = re.compile('Scratching close: (.+? AEST)')
  92. # The times tuple is filled with a dateTime string then a unixtime (seconds since 1970)
  93. times = ['', 0, '', 0]
  94. time_format = '%a %d-%b-%y %I:%M%p'
  95. aest = timezone('Australia/Brisbane')
  96. if this_meta_data:
  97. this_meta_data = this_meta_data.getText()
  98. match = last_published_regex.search(this_meta_data)
  99. if match:
  100. # print(this_venue.name)
  101. # pprint(match)
  102. times[0] = match.group(1)[:-5]
  103. # times[0] = 'Thu 20-Jun-19 7:42AM'
  104. l_time = datetime.datetime.strptime(times[0], time_format)
  105. # print(aest.localize(l_time))
  106. times[1] = model.convert_to_unixtime(aest.localize(l_time))
  107. # print(times[1])
  108. match = close_regex.search(this_meta_data)
  109. if match:
  110. # print(match[1])
  111. times[2] = match.group(1)[:-5]
  112. l_time = datetime.datetime.strptime(times[2], time_format)
  113. # print(aest.localize(l_time))
  114. times[3] = model.convert_to_unixtime(aest.localize(l_time))
  115. # print(times[3])
  116. # The RaceDAy namedTuple is created and filled
  117. race_day = RaceDay(this_venue.state, this_venue.name, this_venue.date_string,
  118. datetime.date.fromtimestamp(times[3]+12*60*60),
  119. this_venue.scratchings_url, times[0], times[1], times[2], times[3])
  120. return race_day
  121. def process_scratchings(this_data, this_venue):
  122. this_soup = BeautifulSoup(this_data, 'html.parser')
  123. try:
  124. this_scr = this_soup.select('div.scratchings')[0]
  125. except IndexError:
  126. return
  127. scratchings_count = this_scr.select('table')[0].select('tr')[2].select('td')[3].getText()
  128. print('{}: scratchings_count {}'.format(this_venue.name, scratchings_count))
  129. header = this_scr.select('h3', text=re.compile('Scratchings'))[0]
  130. div = header.findNext('table')
  131. old_race = 0
  132. race = 0
  133. scratchings = []
  134. for text in div.stripped_strings:
  135. if text[:5] == 'Race ':
  136. match = re.search('^Race ([0-9]+):$', text)
  137. if match:
  138. try:
  139. race = int(match.group(1))
  140. except ValueError:
  141. # This will happily fail in the next assert
  142. race = 0
  143. assert race > old_race, 'race {} ! > old_race {}'.format(race, old_race)
  144. old_race = race
  145. continue
  146. if text[0] == '(':
  147. continue
  148. if len(text) > 0:
  149. if text[0:10] == 'There are ':
  150. continue
  151. try:
  152. int(text[0])
  153. except ValueError:
  154. print('First character in line: {}'.format(text[0]))
  155. print('The start of the offending line is: {}'.format(text[0:10]))
  156. continue
  157. temp_list = Scratching(this_venue.name, this_venue.date, race, text)
  158. scratchings.append(temp_list)
  159. assert len(scratchings) == int(scratchings_count), 'len(scratchings) {} == scratchings_count {}'.format(
  160. len(scratchings), scratchings_count)
  161. pprint(scratchings)
  162. return scratchings