TheCDC

EGR226 HW7 Python

Apr 7th, 2016
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. # Cross platforrm solution for 2016 CBU EGR226 HW7
  4. # by Christopher Chen
  5. import socket
  6.  
  7.  
  8. def get_temp():
  9.     host = "www.surf-forecast.com"
  10.     target = "/breaks/Santa-Monic-Pier/seatemp"
  11.     request_header = "GET {target} HTTP/1.1\nHost: {host}\n\n".format(
  12.         target=target, host=host).encode()
  13.     # socket stuff
  14.     s = socket.socket(
  15.         socket.AF_INET, socket.SOCK_STREAM)
  16.     s.connect((host, 80))
  17.     s.send(request_header)
  18.  
  19.     buf = b""
  20.     res = s.recv(1024)
  21.  
  22.     # this is the delimiter,
  23.     # the presence of which lets us know when to stop listening
  24.     # The input is a bytestring so this must be as well
  25.     tail = b"</html>"
  26.  
  27.     # get the whole page and put it in buf
  28.     while len(res) > 0 and not tail in buf:
  29.         res = s.recv(1014)
  30.         buf += res
  31.  
  32.     # thank goodness the HTML is neatly separated onto separate lines
  33.     # simply filter for lines for ones containing the temperature bit
  34.     # then filter for numerical characters (and periods) in that line.
  35.     found = float(
  36.         ''.join(filter(
  37.             lambda c: c in "0987654321.",
  38.             [l.strip() for l in ''.join(map(chr, buf)).split("\n")
  39.              if "<b>Today's Santa Monica Pier sea temperature is" in l][0],
  40.         )
  41.         )[:-1]
  42.     )
  43.     # algorithm:
  44.     # find the line that contains the sentence about the temp.
  45.     # filter that line for numerals and periods
  46.     # slice off the trailing period that I know is there
  47.     # convert the remainder to float
  48.  
  49.     s.close()
  50.     return found
  51.  
  52.  
  53. def main():
  54.     print("{} C".format(get_temp()))
  55.  
  56. if __name__ == '__main__':
  57.     main()
Advertisement
Add Comment
Please, Sign In to add comment