message_get_one_week_weather.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. from utils.utils_send_serverchan import *
  14. class Weather():
  15. def __init__(self):
  16. self.email_subject = '天气预报'
  17. self.email_title = 'Weather forecast'
  18. self.email_text = '获取数据时间:\n{0}\n{1}\n\n\n\n'.format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
  19. ('-' * 90))
  20. self.logs_handle = LogsHandle()
  21. self.now_day = time.strftime('%Y-%m-%d', time.localtime())
  22. def main(self):
  23. self.logs_handle.logs_write('Weather forecast', '开始获取天气预报数据', 'start', False)
  24. try:
  25. area_code = '59287'
  26. one_week = [
  27. '/tomorrow-%s.htm' % area_code,
  28. '/third-%s.htm' % area_code,
  29. '/fourth-%s.htm' % area_code,
  30. '/fifth-%s.htm' % area_code,
  31. '/sixth-%s.htm' % area_code,
  32. '/seventh-%s.htm' % area_code,
  33. ]
  34. url = "https://tianqi.2345.com/today-%s.htm" % area_code
  35. header = {
  36. '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'
  37. }
  38. response = httpx.get(url=url, headers=header) # 增加headers参数,简单伪装UA
  39. response.encoding = "utf-8"
  40. bs = BeautifulSoup(response.text, 'html.parser') # 这里我们用html.parser解析器
  41. one_week_weather = []
  42. for week in one_week:
  43. a = bs.find_all('a', href=week) # 查找对应元素
  44. a = ' '.join(a[0].text.split())
  45. one_week_weather.append(a)
  46. except Exception as e:
  47. print(e)
  48. self.logs_handle.logs_write('Weather forecast', e, 'error', False)
  49. exit(0)
  50. text = "天气预报: {}获取并发送\n".format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) + '\n'.join(
  51. one_week_weather)
  52. # 推送到 message
  53. GotifyNotifier('天气预报数', text).send_message()
  54. # 推送到 serverchan
  55. # ServerChanNotifier('天气预报数', text.replace('\n', '\n\n')).send_message()
  56. self.logs_handle.logs_write('Weather forecast', '天气预报数据已获取', 'done', False)
  57. if __name__ == "__main__":
  58. L = LogsHandle()
  59. L.logs_write('Weather forecast', '开始获取天气预报数据', 'start', False)
  60. W = Weather()
  61. W.main()
  62. L.logs_write('Weather forecast', '天气预报数据已获取', 'done', False)