Advertisement
jarekmor

energy_tge_mqtt

Mar 28th, 2023 (edited)
994
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. ## Installation of python3 venv and pip:
  2. # sudo apt update
  3. # sudo apt install python3-venv
  4. # sudo apt install python3-pip
  5. ## Create and activate python virtual venv:
  6. # python3 -m venv scrape_ven
  7. # source scrape_venv/bin/activate
  8. ## Install required packages with pip:
  9. # pip install bs4 paho-mqtt
  10.  
  11. import requests
  12. from bs4 import BeautifulSoup
  13. import json
  14. import paho.mqtt.client as mqtt
  15. import time
  16.  
  17. # MQTT broker and topic information
  18. HOST = "192.168.1.5"
  19. TOPIC = "energia/params"
  20. USER = "mqtt"
  21. PASSWD = "mqtt#"
  22.  
  23. # Scrape and send json to mqqt topic
  24. def tge_to_mqtt():
  25.     url = "https://tge.pl/energia-elektryczna-rdn"
  26.     r = requests.get(url)
  27.  
  28.     soup = BeautifulSoup(r.content, 'lxml')
  29.     head = soup.find('table', {'class':"footable table table-hover table-padding"})
  30.     date = soup.find('h4', {'class':'kontrakt-date'}).text
  31.     data = date[-10:]
  32.     table = head.find('tbody')
  33.  
  34.     lista = []
  35.     for row in table.find_all('tr'):
  36.         li = []
  37.         slown = {}
  38.         for col in row.find_all('td'):
  39.             li.append(col.text.replace('\n','').replace('\t',''))
  40.  
  41.         slown = {
  42.                 'Data': data,
  43.                 'Czas': li[0],
  44.                 'FIXING_I' : [{'Kurs (PLN/MWh)': li[1]},{'Wolumen (MWh)': li[2]}],
  45.                 'FIXING_II': [{'Kurs (PLN/MWh)': li[3]}, {'Wolumen (MWh)': li[4]}],
  46.                 'Notowania_ciagle': [{'Kurs (PLN/MWh)': li[5]},{'Wolumen (MWh)': li[6]}],    
  47.             }
  48.         lista.append(slown)
  49.  
  50.     return json.dumps(lista, indent=4)
  51.  
  52. if __name__ == "__main__":
  53.     while True:    
  54.         # Create MQTT client and connect to the broker
  55.         client = mqtt.Client()
  56.         client.username_pw_set(USER, PASSWD)
  57.         client.connect(HOST, 1883, 60)
  58.         client.publish(TOPIC, payload=tge_to_mqtt())
  59.         time.sleep(3600)                                # wait 3600 sec
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement