Spaces:
Build error
Build error
Update tariff_scraper.py
Browse files- tariff_scraper.py +18 -35
tariff_scraper.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
import requests
|
| 3 |
from bs4 import BeautifulSoup
|
| 4 |
|
|
@@ -8,43 +7,27 @@ def scrape_tariff_data(url):
|
|
| 8 |
response.raise_for_status() # Raise an error for bad responses
|
| 9 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 10 |
|
| 11 |
-
# Extract
|
| 12 |
-
# Assume tariff data is in <table> tags
|
| 13 |
tariff_sections = soup.find_all('table')
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
for section in tariff_sections:
|
| 17 |
-
|
| 18 |
-
for row in
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
data.append(row_text)
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
def main():
|
| 30 |
-
st.title("Electricity Tariff Scraper")
|
| 31 |
-
st.write("Enter the URL of the electricity tariff page:")
|
| 32 |
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
if st.button("Scrape"):
|
| 36 |
-
if url:
|
| 37 |
-
with st.spinner("Scraping data..."):
|
| 38 |
-
data = scrape_tariff_data(url)
|
| 39 |
-
if isinstance(data, list):
|
| 40 |
-
st.success("Data scraped successfully!")
|
| 41 |
-
st.write("Here is a preview of the data:")
|
| 42 |
-
for row in data[:10]: # Show only the first 10 rows for readability
|
| 43 |
-
st.write(row)
|
| 44 |
-
else:
|
| 45 |
-
st.error(data)
|
| 46 |
-
else:
|
| 47 |
-
st.error("Please enter a valid URL.")
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
| 1 |
import requests
|
| 2 |
from bs4 import BeautifulSoup
|
| 3 |
|
|
|
|
| 7 |
response.raise_for_status() # Raise an error for bad responses
|
| 8 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 9 |
|
| 10 |
+
# Extract the table containing tariff data
|
|
|
|
| 11 |
tariff_sections = soup.find_all('table')
|
| 12 |
+
if not tariff_sections:
|
| 13 |
+
return "Error: No tables found on the webpage."
|
| 14 |
|
| 15 |
+
tariff_data = {}
|
| 16 |
for section in tariff_sections:
|
| 17 |
+
rows = section.find_all('tr') # Find all rows in the table
|
| 18 |
+
for row in rows:
|
| 19 |
+
columns = row.find_all('td') # Extract all table data (td) columns
|
| 20 |
+
if len(columns) >= 5: # Check if the row has enough columns
|
| 21 |
+
category = columns[1].get_text(strip=True) # Tariff category
|
| 22 |
+
rate = columns[4].get_text(strip=True) # Variable charges (Rs./kWh)
|
|
|
|
| 23 |
|
| 24 |
+
# Add to the dictionary if the rate is numeric
|
| 25 |
+
if rate.replace('.', '', 1).isdigit():
|
| 26 |
+
tariff_data[category] = float(rate)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
if not tariff_data:
|
| 29 |
+
return "Error: No valid tariff rates found."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
return tariff_data # Return structured tariff data as a dictionary
|
| 32 |
+
except Exception as e:
|
| 33 |
+
return f"An error occurred: {e}"
|