get_one_week_weather.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # -*- coding: utf-8 -*-
  2. '''
  3. 获取天气预报
  4. '''
  5. import os
  6. import sys
  7. sys.path.append(os.path.join(os.path.abspath(__file__).split('AutoInfo')[0] + 'AutoInfo'))
  8. SUB_PROJECT_NAME = "获取天气预报"
  9. PROJECT_PATH = os.path.join(os.path.abspath(__file__).split('AutoInfo')[0] + 'AutoInfo')
  10. import time
  11. import json
  12. from bs4 import BeautifulSoup
  13. import httpx
  14. from utils.utils_gotify import GotifyNotifier
  15. class Weather():
  16. def main(self):
  17. print('开始获取天气预报数据')
  18. try:
  19. area_code = '59287'
  20. one_week = [
  21. '/tomorrow-%s.htm' % area_code,
  22. '/third-%s.htm' % area_code,
  23. '/fourth-%s.htm' % area_code,
  24. '/fifth-%s.htm' % area_code,
  25. '/sixth-%s.htm' % area_code,
  26. '/seventh-%s.htm' % area_code,
  27. ]
  28. url = "https://tianqi.2345.com/today-%s.htm" % area_code
  29. header = {'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'}
  30. response = httpx.get(url=url, headers=header)
  31. response.encoding = "utf-8"
  32. bs = BeautifulSoup(response.text, 'html.parser')
  33. one_week_weather = []
  34. for week in one_week:
  35. a = bs.find_all('a', href=week)
  36. a = ' '.join(a[0].text.split())
  37. one_week_weather.append(a)
  38. except Exception as e:
  39. print(e)
  40. print('Weather forecast')
  41. exit(0)
  42. text = "天气预报: {}获取并发送\n".format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) + '\n'.join(
  43. one_week_weather)
  44. # 推送到 message
  45. GotifyNotifier('天气预报数', text, 'weather').send_message()
  46. print('天气预报数据已获取')
  47. if __name__ == "__main__":
  48. W = Weather().main()