Spaces:
Build error
Build error
Rename tariff_scraper.py to scraper.py
Browse files- scraper.py +69 -0
- tariff_scraper.py +0 -48
scraper.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
from bs4 import BeautifulSoup
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import time
|
| 5 |
+
from random import randint
|
| 6 |
+
|
| 7 |
+
def scrape_tariffs(urls):
|
| 8 |
+
data = []
|
| 9 |
+
for url in urls:
|
| 10 |
+
try:
|
| 11 |
+
response = requests.get(url, timeout=10) # Added timeout
|
| 12 |
+
response.raise_for_status() # Raise exception for bad status codes (4xx, 5xx)
|
| 13 |
+
|
| 14 |
+
# Scrape data if the response is OK
|
| 15 |
+
if response.status_code == 200:
|
| 16 |
+
soup = BeautifulSoup(response.content, "html.parser")
|
| 17 |
+
rows = soup.find_all("tr")
|
| 18 |
+
|
| 19 |
+
for row in rows:
|
| 20 |
+
cells = row.find_all("td")
|
| 21 |
+
if len(cells) >= 2:
|
| 22 |
+
try:
|
| 23 |
+
data.append({
|
| 24 |
+
"category": cells[0].text.strip(),
|
| 25 |
+
"rate": float(cells[1].text.strip().replace(",", ""))
|
| 26 |
+
})
|
| 27 |
+
except ValueError:
|
| 28 |
+
continue
|
| 29 |
+
|
| 30 |
+
except requests.exceptions.RequestException as e:
|
| 31 |
+
print(f"Error fetching data from {url}: {e}")
|
| 32 |
+
print("Retrying...")
|
| 33 |
+
|
| 34 |
+
# Retry logic in case of failure (max 3 retries with random delay)
|
| 35 |
+
retries = 3
|
| 36 |
+
while retries > 0:
|
| 37 |
+
time.sleep(randint(1, 3)) # Sleep for a random time before retrying
|
| 38 |
+
retries -= 1
|
| 39 |
+
try:
|
| 40 |
+
response = requests.get(url, timeout=10)
|
| 41 |
+
response.raise_for_status()
|
| 42 |
+
if response.status_code == 200:
|
| 43 |
+
soup = BeautifulSoup(response.content, "html.parser")
|
| 44 |
+
rows = soup.find_all("tr")
|
| 45 |
+
|
| 46 |
+
for row in rows:
|
| 47 |
+
cells = row.find_all("td")
|
| 48 |
+
if len(cells) >= 2:
|
| 49 |
+
try:
|
| 50 |
+
data.append({
|
| 51 |
+
"category": cells[0].text.strip(),
|
| 52 |
+
"rate": float(cells[1].text.strip().replace(",", ""))
|
| 53 |
+
})
|
| 54 |
+
except ValueError:
|
| 55 |
+
continue
|
| 56 |
+
break
|
| 57 |
+
except requests.exceptions.RequestException:
|
| 58 |
+
print(f"Retry failed: {e}")
|
| 59 |
+
continue
|
| 60 |
+
|
| 61 |
+
# Sleep between requests to avoid hitting the servers too quickly
|
| 62 |
+
time.sleep(randint(2, 5))
|
| 63 |
+
|
| 64 |
+
if data:
|
| 65 |
+
df = pd.DataFrame(data)
|
| 66 |
+
df.to_csv("data/tariffs.csv", index=False)
|
| 67 |
+
print("Tariff data saved successfully.")
|
| 68 |
+
else:
|
| 69 |
+
print("No tariff data found.")
|
tariff_scraper.py
DELETED
|
@@ -1,48 +0,0 @@
|
|
| 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}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|