Spaces:
Build error
Build error
Update tariff_scraper.py
Browse files- tariff_scraper.py +6 -31
tariff_scraper.py
CHANGED
|
@@ -1,17 +1,16 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
import requests
|
| 3 |
from bs4 import BeautifulSoup
|
| 4 |
|
| 5 |
def scrape_tariff_data(url):
|
| 6 |
try:
|
| 7 |
response = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
|
| 8 |
-
response.raise_for_status()
|
| 9 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 10 |
-
|
| 11 |
-
#
|
| 12 |
-
# Assume tariff data is in <table> tags
|
| 13 |
tariff_sections = soup.find_all('table')
|
| 14 |
|
|
|
|
| 15 |
data = []
|
| 16 |
for section in tariff_sections:
|
| 17 |
table_rows = section.find_all('tr')
|
|
@@ -19,32 +18,8 @@ def scrape_tariff_data(url):
|
|
| 19 |
row_text = ' | '.join(
|
| 20 |
col.get_text(strip=True) for col in row.find_all(['th', 'td'])
|
| 21 |
)
|
| 22 |
-
if row_text:
|
| 23 |
data.append(row_text)
|
| 24 |
-
|
| 25 |
-
return data # Returns a list of row strings
|
| 26 |
except Exception as e:
|
| 27 |
return f"An error occurred: {e}"
|
| 28 |
-
|
| 29 |
-
def main():
|
| 30 |
-
st.title("Electricity Tariff Scraper")
|
| 31 |
-
st.write("Enter the URL of the electricity tariff page:")
|
| 32 |
-
|
| 33 |
-
url = st.text_input("URL", "https://iesco.com.pk/index.php/customer-services/tariff-guide")
|
| 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 |
-
if __name__ == "__main__":
|
| 50 |
-
main()
|
|
|
|
|
|
|
| 1 |
import requests
|
| 2 |
from bs4 import BeautifulSoup
|
| 3 |
|
| 4 |
def scrape_tariff_data(url):
|
| 5 |
try:
|
| 6 |
response = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
|
| 7 |
+
response.raise_for_status()
|
| 8 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 9 |
+
|
| 10 |
+
# Find all tables in the webpage
|
|
|
|
| 11 |
tariff_sections = soup.find_all('table')
|
| 12 |
|
| 13 |
+
# Extract data row by row
|
| 14 |
data = []
|
| 15 |
for section in tariff_sections:
|
| 16 |
table_rows = section.find_all('tr')
|
|
|
|
| 18 |
row_text = ' | '.join(
|
| 19 |
col.get_text(strip=True) for col in row.find_all(['th', 'td'])
|
| 20 |
)
|
| 21 |
+
if row_text:
|
| 22 |
data.append(row_text)
|
| 23 |
+
return data
|
|
|
|
| 24 |
except Exception as e:
|
| 25 |
return f"An error occurred: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|