Engineer786 commited on
Commit
ee76d20
·
verified ·
1 Parent(s): ea74946

Update tariff_scraper.py

Browse files
Files changed (1) hide show
  1. 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 specific elements based on the webpage structure
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')
18
- for row in table_rows:
19
- row_text = ' | '.join(
20
- col.get_text(strip=True) for col in row.find_all(['th', 'td'])
21
- )
22
- if row_text: # Add the row text only if it contains data
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
 
 
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}"