Skip to content

Instantly share code, notes, and snippets.

@thejoltjoker
Last active October 20, 2023 15:23
Show Gist options
  • Save thejoltjoker/213aa2240ccf6dd64f8f2025e2d7af3c to your computer and use it in GitHub Desktop.
Save thejoltjoker/213aa2240ccf6dd64f8f2025e2d7af3c to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
main.py
This script demonstrates how to extract temperature values from a web page using Selenium and regular expressions.
"""
import re
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from fastapi import FastAPI
from fastapi.responses import ORJSONResponse
# Api
app = FastAPI()
# Initialize a Selenium WebDriver (in this case, Chrome)
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images": 2}
chrome_options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(options=chrome_options)
@app.get("/temperature/", response_class=ORJSONResponse)
async def get_temperature():
return ORJSONResponse([{"celsius": scrape_temperature()}])
def extract_temperature(text):
"""
Extracts the temperature value (in Celsius) from a given text string.
Args:
text (str): The input text containing the temperature value.
Returns:
float or None: The extracted temperature value as a float, or None if not found.
"""
# Define a regular expression pattern to match the temperature value
pattern = r'([-+]?\d*\.?\d+)[°C]'
# Search for the pattern in the input text
match = re.search(pattern, text)
if match:
# Extract the matched temperature value and convert it to a float
temperature = float(match.group(1))
return temperature
else:
return None
def scrape_temperature():
"""
The main function to run the script.
"""
# Open a web page with temperature information
driver.get("https://portal.loggamera.se/PublicViews/OverviewInside?id=22")
# Find the element on the web page with the specified class name
elem = driver.find_element(By.CLASS_NAME, "display-value")
# Extract and print the temperature value from the element's text
temperature = extract_temperature(elem.text)
return temperature
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment