Code: Select all
from bs4 import BeautifulSoup
import requests
def get_power_value():
# Send the request with Basic Authentication
url = 'http://192.168.178.XXX/status.html'
username = 'XXXXXXX'
password = 'XXXXXXX'
response = requests.get(url, auth=(username, password))
if response.status_code != 200:
raise Exception(f"Failed to fetch page, status code: {response.status_code}")
# Parse the HTML content
soup = BeautifulSoup(response.text, 'html.parser')
# Find all script tags
scripts = soup.find_all('script')
# Regular expression to match JavaScript variable assignments
var_regex = re.compile(r'var\s+(\w+)\s*=\s*"([^"]+)"')
# Initialize variables
webdata_now_p = None
webdata_today_e = None
# Search through the script contents
for script in scripts:
script_content = script.string
if script_content:
for match in var_regex.finditer(script_content):
var_name, var_value = match.groups()
if var_name == 'webdata_now_p':
webdata_now_p = var_value
elif var_name == 'webdata_today_e':
webdata_today_e = var_value
# Ensure both values are found
if webdata_now_p is None or webdata_today_e is None:
raise Exception("Failed to find one or both variables in the HTML")
# Convert webdata_today_e to float and multiply by 1000
try:
webdata_today_e = float(webdata_today_e) * 1000
except ValueError:
raise Exception(f"Error converting webdata_today_e to float: {webdata_today_e}")
print("Aktuell:", webdata_now_p)
print("Gesamt:", webdata_today_e)
# Return the extracted values
return webdata_now_p, webdata_today_e