def fetchtraxelektronikdata(): url =…
- User
def fetch_traxelektronik_data(): url = 'https://www.traxelektronik.pl/pogoda/zbiorcza.php?RejID=10' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser')
stations = [] temperatures = [] table_rows = soup.find_all('tr')[2:] for row in table_rows: columns = row.find_all('td') if len(columns) > 1: station = columns[0].get_text(strip=True) temperature = columns[1].get_text(strip=True) if temperature != "-": stations.append(station) # Keep original station names temperatures.append(temperature) return stations, temperaturesdef fetch_netatmo_data(): url = "https://api.netatmo.com/api/getpublicdata" params = { "lat_ne": 53, "lon_ne": 22, "lat_sw": 51, "lon_sw": 19, "required_data": "temperature", "filter": "true", "access_token": "66e1e80975134797710422cd|ced1212a511bc0fb5ac094377465ed2b" }
response = requests.get(url, params=params) if response.status_code != 200: print(f"Error fetching Netatmo data: {response.status_code}") return [], [], [] data = json.loads(response.text) stations = [] temperatures = [] coordinates = [] # List of cities to exclude excluded_cities = ["Płońsk", "Łochów"] for station in data.get('body', []): place = station.get('place', {}) location = place.get('location') if location: lon, lat = location if is_in_masovian(lat, lon): city = place.get('city', 'Unknown') if city in excluded_cities: # Skip this station continue for module, module_data in station.get('measures', {}).items(): if 'temperature' in module_data.get('type', []): res = module_data.get('res', {}) if res: latest_timestamp = max(res.keys()) temperature = res[latest_timestamp][0] stations.append(city) temperatures.append(temperature) coordinates.append((lat, lon)) break return stations, temperatures, coordinatesdef fetch_imgw_data(): url = "https://rafalraczynski.com.pl/imgw/dane-imgw/getJSON.php?type=table&province=14&sort=temp&order=asc" response = requests.get(url) if response.status_code == 200: data = response.json() else: return [], [], []
target_stations = [ "ANDRZEJEWO", "BORKOWO", "CZARNOWO", "KAZANÓW", "RUSZKOWICE", "RYBIENKO", "RZĄŚNIK WŁOŚCIAŃSKI", "WIELGOLAS" ] stations = [] temperatures = [] station_ids = [] for item in data: statName = item.get('statName') temp = item.get('temp') if statName and temp and statName.upper() in target_stations: stations.append(statName) temperatures.append(temp) station_ids.append(item.get('statId', 'Unknown')) return stations, temperatures, station_idsIn there, can you write a fetch wunderground function, where it will fetch wunderground data from the next stations: IKRAJW1, IPOLIT1. The data would be in F, so we need to convert it to Celcius. Print the results. Here's the URL example for the fetching: https://www.wunderground.com/dashboard/pws/IPOLIT1 In the code element it looks like that (the tfield with temperature data): 7.0
- Assistant
Certainly! Below is the
fetch_wunderground_datafunction that fetches temperature data from the specified Weather Underground stations (IKRAJW1andIPOLIT1), converts the temperatures from Fahrenheit to Celsius, and prints the results.Make sure you have the necessary libraries installed. If not, you can install them using
pip:pip install requests beautifulsoup4Here's the complete code:
import requests from bs4 import BeautifulSoup def fetch_wunderground_data(): stations = ["IKRAJW1", "IPOLIT1"] base_url = "https://www.wunderground.com/dashboard/pws/{}" station_names = [] temperatures_c = [] for station in stations: url = base_url.format(station) try: response = requests.get(url, timeout=10) response.raise_for_status() except requests.RequestException as e: print(f"Error fetching data for station {station}: {e}") continue soup = BeautifulSoup(response.text, 'html.parser') temp_span = soup.find('span', class_="wu-value wu-value-to") if temp_span: try: temp_f_str = temp_span.get_text(strip=True) temp_f = float(temp_f_str) temp_c = (temp_f - 32) * 5.0/9.0 temp_c = round(temp_c, 1) # Round to one decimal place station_names.append(station) temperatures_c.append(temp_c) except ValueError: print(f"Error parsing temperature for station {station}: '{temp_span.get_text(strip=True)}'") else: print(f"Temperature data not found for station {station}") # Print the results for station, temp in zip(station_names, temperatures_c): print(f"Station {station}: {temp}°C") return station_names, temperatures_c # Example usage if __name__ == "__main__": fetch_wunderground_data()Explanation of the Code
-
Imports:
requestsis used to make HTTP requests to fetch the webpage data.BeautifulSoupfrombs4is used to parse the HTML content and extract temperature data.
-
Function
fetch_wunderground_data():- Stations List: Contains the station IDs you want to fetch data from (
IKRAJW1andIPOLIT1). - Loop Through Stations: For each station, it constructs the URL and makes a GET request.
- Error Handling: Uses
try-exceptblocks to handle network-related errors and issues with parsing the temperature. - Parsing HTML:
- Looks for a
<span>tag with the class"wu-value wu-value-to", which contains the temperature in Fahrenheit. - Extracts the temperature text, converts it to a float, and then converts it to Celsius using the formula:
[ \text{Celsius} = (\text{Fahrenheit} - 32) \times \frac{5}{9} ] - Rounds the Celsius temperature to one decimal place for readability.
- Looks for a
- Storing Results: Appends the station ID and the converted temperature to their respective lists.
- Printing Results: After fetching and converting all data, it prints each station's temperature in Celsius.
- Return Values: Returns two lists containing station names and their corresponding temperatures in Celsius.
- Stations List: Contains the station IDs you want to fetch data from (
-
Example Usage:
- The
if __name__ == "__main__":block ensures that thefetch_wunderground_data()function is called only when the script is run directly, not when imported as a module. - When executed, it will print the temperatures for
IKRAJW1andIPOLIT1in Celsius.
- The
Sample Output
When you run the script, the output will look something like this (actual temperatures will vary based on real-time data):
Station IKRAJW1: 21.7°C Station IPOLIT1: 19.4°CNotes
- Timeout: A timeout of 10 seconds is set for each HTTP request to prevent the script from hanging indefinitely if the server doesn't respond.
- Error Messages: The script provides informative error messages if it encounters issues fetching or parsing data for any station.
- Extensibility: You can easily add more stations to the
stationslist if needed.
Feel free to integrate this function into your existing codebase alongside the other data-fetching functions you have.
-