Engineer786 commited on
Commit
9e63bdc
·
verified ·
1 Parent(s): 908ed95

Update tariff_scraper.py

Browse files
Files changed (1) hide show
  1. tariff_scraper.py +43 -28
tariff_scraper.py CHANGED
@@ -1,33 +1,48 @@
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() # 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}"
 
1
  import requests
2
  from bs4 import BeautifulSoup
3
+ import pandas as pd
4
 
5
+ def fetch_tariff_data(url):
6
+ """Fetch tariff data from the provided URL."""
7
+ response = requests.get(url)
8
+ if response.status_code != 200:
9
+ raise Exception(f"Failed to fetch data from {url}, status code: {response.status_code}")
10
+
11
+ soup = BeautifulSoup(response.content, 'html.parser')
12
+ sections = soup.find_all('tr', id='table_heading')
13
+
14
+ tariff_data = {}
15
+ for section in sections:
16
+ heading = section.find('td').get_text(strip=True)
17
+ rows = section.find_next_siblings('tr')
18
+
19
+ data = []
20
+ for row in rows:
21
+ columns = row.find_all('td')
22
+ if len(columns) >= 5: # Ensure it has the expected number of columns
23
+ data.append({
24
+ "Sr. No.": columns[0].get_text(strip=True),
25
+ "Category": columns[1].get_text(strip=True),
26
+ "Fixed Rs/Cons/M": columns[2].get_text(strip=True),
27
+ "Fixed Rs/kW/M": columns[3].get_text(strip=True),
28
+ "Variable Rs/kWh": columns[4].get_text(strip=True),
29
+ })
30
+
31
+ tariff_data[heading] = pd.DataFrame(data)
32
+
33
+ return tariff_data
34
+
35
+ def save_tariff_data(tariff_data, file_path):
36
+ """Save the fetched tariff data to an Excel file."""
37
+ with pd.ExcelWriter(file_path) as writer:
38
+ for heading, df in tariff_data.items():
39
+ df.to_excel(writer, sheet_name=heading[:31], index=False)
40
+
41
+ if __name__ == "__main__":
42
+ url = "https://iesco.com.pk/index.php/customer-services/tariff-guide"
43
  try:
44
+ tariff_data = fetch_tariff_data(url)
45
+ save_tariff_data(tariff_data, "tariff_data.xlsx")
46
+ print("Tariff data successfully saved to tariff_data.xlsx")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  except Exception as e:
48
+ print(f"Error: {e}")