weather7d.py 2.0 KB

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