delvin-fil

Парсер текущей метеобстановки

Oct 6th, 2020 (edited)
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.33 KB | None | 0 0
  1. #!/usr/bin/env python3.8
  2. # -*- coding: utf-8 -*-
  3. import time
  4. start_time = time.time()
  5. import warnings
  6. warnings.filterwarnings("ignore")
  7. import locale
  8. locale.setlocale(locale.LC_ALL, '')
  9. import math
  10. import json
  11. import re
  12. import sys
  13. import requests
  14. import datetime
  15. from datetime import date
  16. from math import radians as rad, degrees as deg
  17. from grab import Grab
  18. import optparse
  19.  
  20. first_re = re.compile(r'^\d{3}$')
  21. parser = optparse.OptionParser()
  22. parser.set_defaults(temperature=False, pressures=False, clouds=False)
  23. parser.add_option('-t',
  24.                   '--temperature',
  25.                   action='store_true',
  26.                   dest='temperature')
  27. parser.add_option('-p', '--pressures', action='store_true', dest='pressures')
  28. parser.add_option('-c', '--clouds', action='store_true', dest='clouds')
  29. parser.add_option('-w', '--wind ', action='store_true', dest='winds')
  30. parser.add_option('-s', '--wspeed', action='store_true', dest='wind speed ')
  31.  
  32. (options, args) = parser.parse_args()
  33.  
  34. localtime = time.localtime(time.time())
  35. hour = localtime[3]
  36. minute = localtime[4]
  37.  
  38. headers = {
  39.     'User-Agent': ('Mozilla/5.0 (Windows NT 6.0; rv:14.0) Gecko/20100101 '
  40.                    'Firefox/14.0.1'),
  41.     'Accept':
  42.     'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  43.     'Accept-Language':
  44.     'ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3',
  45.     'Accept-Encoding':
  46.     'gzip, deflate',
  47.     'Connection':
  48.     'keep-alive',
  49.     'DNT':
  50.     '1'
  51. }
  52.  
  53. cmd = 'sensorsNearby'
  54. uuid = 'you_uuid'  # narodmon.ru/api
  55. api_key = 'you_apikey'  # narodmon.ru/api
  56. appid = 'you_appid' # narodmon.ru/api
  57. # Ленинск-Кузнецкий     lat=54&lon=86
  58. lat = '54.65'  # Home 9  86.184826%2C54.681399
  59. lng = '86.18'  # Home 9  lat=54.643689&lon=86.199094
  60. lang = 'ru'
  61. radius = 50
  62. types = '1,2'
  63.  
  64. geturi = f'http://narodmon.ru/api/sensorsNearby?lat={lat}&lng={lng}&radius={radius}&uuid={uuid}&api_key={api_key}&lang={lang}'
  65. #print (geturi)
  66. windy = Grab(timeout=300)
  67. windy.go("https://yandex.ru/pogoda/leninsk-kuznetskiy/details")
  68.  
  69. davl = ''
  70.  
  71.  
  72. def pressave():
  73.     my_file = open("/home/pressure.txt", "r")
  74.     pressave = float(my_file.read())
  75.     my_file.close()
  76.     return pressave
  77.  
  78.  
  79. def windspeed():
  80.     try:
  81.         speed = windy.xpath_text('//*[@class="wind-speed"]')
  82.         speed = re.sub(r',', '.', speed)
  83.         speed = round(int(float(speed)), 0)
  84.     except IndexError:
  85.         speed = 0
  86.     return speed
  87.  
  88.  
  89. def pole():
  90.     try:
  91.         pole = windy.xpath_list(
  92.             '//*[@class="forecast-fields__value"]')[1].text_content()
  93.     except IndexError:
  94.         pole = "Нет данных"
  95.     return pole
  96.  
  97.  
  98. def wind():
  99.     try:
  100.         direction = windy.xpath_text('//*[@class=" icon-abbr"]')
  101.     except IndexError:
  102.         direction = "Штиль"
  103.     if direction == "С":
  104.         direction = "Северный"
  105.     elif direction == "СВ":
  106.         direction = "Северо-восточный"
  107.     elif direction == "В":
  108.         direction = "Восточный"
  109.     elif direction == "ЮВ":
  110.         direction = "Юго-восточный"
  111.     elif direction == "Ю":
  112.         direction = "Южный"
  113.     elif direction == "ЮЗ":
  114.         direction = "Юго-западный"
  115.     elif direction == "З":
  116.         direction = "Западный"
  117.     elif direction == "СЗ":
  118.         direction = "Северо-западный"
  119.     return direction
  120.  
  121.  
  122. def cloudy():
  123.     cloud = Grab(timeout=300)
  124.     cloud.go("https://yandex.ru/pogoda/leninsk-kuznetskiy")
  125.     cloud = cloud.xpath_text('//*[@class="link__feelings fact__feelings"]')
  126.     cloud = re.sub(r"Ощущается как.*", "", cloud)
  127.     #print(cloud)
  128.     return cloud
  129.  
  130.  
  131. def pressure():
  132.     WeHtm = requests.post(geturi, headers=headers).text
  133.     fact = json.loads(WeHtm)
  134.     devd = 2
  135.     sensd = 1
  136.  
  137.     try:
  138.         davl1 = fact['devices'][devd]['sensors'][sensd]['value']
  139.         locat = fact['devices'][devd]['location']
  140.     except IndexError:
  141.         devd = 4
  142.         davl1 = fact['devices'][devd]['sensors'][0]['value']
  143.         locat = fact['devices'][devd]['location']
  144.     except IndexError:
  145.         devd = 3
  146.         davl1 = fact['devices'][devd]['sensors'][sensd]['value']
  147.         locat = fact['devices'][devd]['location']
  148.     except IndexError:
  149.         devd = 2
  150.         davl1 = fact['devices'][devd]['sensors'][sensd]['value']
  151.         locat = fact['devices'][devd]['location']
  152.     except IndexError:
  153.         devd = 1
  154.         davl1 = fact['devices'][devd]['sensors'][sensd]['value']
  155.         locat = fact['devices'][devd]['location']
  156.     davl = davl1
  157.     return davl, locat
  158.  
  159.  
  160. def temper():
  161.     WeHtm = requests.post(geturi, headers=headers).text
  162.     devt = -1
  163.     tra = 0
  164.     senst = 0
  165.     fact = json.loads(WeHtm)
  166.     unit = fact['devices'][devt]['sensors'][senst]['unit']
  167.     if unit == '°':
  168.         tra = 0
  169.     else:
  170.         tra = 1
  171.     temp1 = fact['devices'][devt]['sensors'][tra]['value']
  172.     if temp1 > 40:
  173.         devt = 3
  174.         temp1 = fact['devices'][devt]['sensors'][tra]['value']
  175.     if temp1 > 40:
  176.         devt = 2
  177.         temp1 = fact['devices'][devt]['sensors'][tra]['value']
  178.     if temp1 > 40:
  179.         devt = 1
  180.         temp1 = fact['devices'][devt]['sensors'][tra]['value']
  181.     if temp1 > 40:
  182.         devt = 0
  183.         temp1 = fact['devices'][devt]['sensors'][tra]['value']
  184.     return temp1
  185.  
  186.  
  187. # ⇑⇓●
  188.  
  189.  
  190. def comparison():
  191.     if pressave() > pressure()[0]:
  192.         comp = "Понижение ▼"
  193.     if pressave() == pressure()[0]:
  194.         comp = "Неизменно ●"
  195.     if pressave() < pressure()[0]:
  196.         comp = "Повышение ▲"
  197.     return comp
  198.  
  199.  
  200. locate = (pressure()[1])
  201. locate = re.sub(r'Ленинск-Кузнецкий, ', '', locate)
  202.  
  203. if len(str(minute)) < 2:
  204.     minute = '0' + str(minute)
  205.  
  206. with open("/home/pressure.txt", "w") as file:
  207.     file.write(str(pressure()[0]))
  208.  
  209. if options.temperature:
  210.     print(temper(), "°C")
  211. if options.pressures:
  212.     print(f"{pressure()[0]} мм.р.с., {locate}")
  213. if options.clouds:
  214.     print(f"{cloudy()}")
  215. '''print (f"wind {wind()}")
  216. print(f"windspeed {windspeed()} m.c.")
  217. print(f"comparison {comparison()}")
  218. print("Магнитное поле", pole())'''
  219. #print(temper(), "°C")
  220. #print(f"{pressure()[0]} мм.р.с., {locate}")
  221.  
  222. end = round(time.time() - start_time, 2)
  223. print("\n--- %s seconds ---" % (end))
  224.  
Add Comment
Please, Sign In to add comment