message_get_one_week_weather.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # -*- coding: utf-8 -*-
  2. '''
  3. 获取天气预报
  4. '''
  5. import os
  6. import sys
  7. import time
  8. from datetime import datetime
  9. from bs4 import BeautifulSoup
  10. sys.path.append(os.path.join(os.path.abspath(__file__).split('auto')[0] + 'auto'))
  11. from utils.utils_logs_handle import LogsHandle
  12. from utils.utils_send_gotify import *
  13. class Weather():
  14. def __init__(self):
  15. self.email_subject = '天气预报'
  16. self.email_title = 'Weather forecast'
  17. self.email_text = '获取数据时间:\n{0}\n{1}\n\n\n\n'.format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
  18. ('-' * 90))
  19. self.logs_handle = LogsHandle()
  20. self.now_day = time.strftime('%Y-%m-%d', time.localtime())
  21. def main(self):
  22. self.logs_handle.logs_write('Weather forecast', '开始获取天气预报数据', 'start', False)
  23. try:
  24. area_code = '59287'
  25. one_week = [
  26. '/tomorrow-%s.htm' % area_code,
  27. '/third-%s.htm' % area_code,
  28. '/fourth-%s.htm' % area_code,
  29. '/fifth-%s.htm' % area_code,
  30. '/sixth-%s.htm' % area_code,
  31. '/seventh-%s.htm' % area_code,
  32. ]
  33. url = "https://tianqi.2345.com/today-%s.htm" % area_code
  34. header = {
  35. 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8'
  36. }
  37. response = httpx.get(url=url, headers=header) # 增加headers参数,简单伪装UA
  38. response.encoding = "utf-8"
  39. bs = BeautifulSoup(response.text, 'html.parser') # 这里我们用html.parser解析器
  40. one_week_weather = []
  41. for week in one_week:
  42. a = bs.find_all('a', href=week) # 查找对应元素
  43. a = ' '.join(a[0].text.split())
  44. one_week_weather.append(a)
  45. except Exception as e:
  46. print(e)
  47. self.logs_handle.logs_write('Weather forecast', e, 'error', False)
  48. exit(0)
  49. text = "天气预报: {}获取并发送\n".format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) + '\n'.join(
  50. one_week_weather)
  51. # 推送到 message
  52. GotifyNotifier('天气预报数', text, 'A9KF--mx_12PjSu').send_message()
  53. self.logs_handle.logs_write('Weather forecast', '天气预报数据已获取', 'done', False)
  54. if __name__ == "__main__":
  55. L = LogsHandle()
  56. L.logs_write('Weather forecast', '开始获取天气预报数据', 'start', False)
  57. W = Weather()
  58. W.main()
  59. L.logs_write('Weather forecast', '天气预报数据已获取', 'done', False)