Engineer786 commited on
Commit
5a82106
·
verified ·
1 Parent(s): bc3f9ef

Update tariff_scraper.py

Browse files
Files changed (1) hide show
  1. tariff_scraper.py +18 -33
tariff_scraper.py CHANGED
@@ -1,46 +1,31 @@
1
  import requests
2
  from bs4 import BeautifulSoup
3
 
4
- def scrape_tariff_data(url="https://iesco.com.pk/index.php/customer-services/tariff-guide"):
5
- """
6
- Scrapes tariff rates from the IESCO tariff guide page.
7
-
8
- Parameters:
9
- url (str): The URL of the tariff guide page.
10
-
11
- Returns:
12
- dict: A dictionary containing tariff rates for different categories.
13
- str: Error message if scraping fails.
14
- """
15
  try:
 
16
  response = requests.get(url)
17
- response.raise_for_status() # Raise error for bad responses
18
  soup = BeautifulSoup(response.text, 'html.parser')
19
 
20
- # Locate the main table containing the tariff data
21
- table = soup.find("table")
22
  if not table:
23
- return "No table found on the page. Please verify the URL."
24
 
25
- # Extract tariff data into a dictionary
26
- tariff_rates = {}
27
- table_rows = table.find_all("tr") # Get all rows in the table
28
- for row in table_rows:
29
- cells = row.find_all("td")
30
- if len(cells) >= 2: # Ensure row has enough columns (category and rate)
31
- category = cells[0].get_text(strip=True)
32
- rate = cells[1].get_text(strip=True)
33
-
34
- # Parse rate into a float
35
- try:
36
- rate_value = float(rate.replace(",", "").split()[0]) # Clean and parse rate
37
- tariff_rates[category] = rate_value
38
- except ValueError:
39
- continue # Skip rows with invalid rate values
40
 
41
- if not tariff_rates:
42
- return "No valid tariff rates found in the table."
 
 
 
 
 
 
43
 
44
- return tariff_rates
45
  except Exception as e:
46
  return f"An error occurred while scraping: {e}"
 
1
  import requests
2
  from bs4 import BeautifulSoup
3
 
4
+ def scrape_tariff_data(url):
 
 
 
 
 
 
 
 
 
 
5
  try:
6
+ # Fetch the webpage
7
  response = requests.get(url)
8
+ response.raise_for_status()
9
  soup = BeautifulSoup(response.text, 'html.parser')
10
 
11
+ # Find the table containing tariff data
12
+ table = soup.find("table") # Adjust this if the table has specific attributes like class or id
13
  if not table:
14
+ return "Error: Could not find the tariff table on the page."
15
 
16
+ # Extract table rows
17
+ rows = table.find_all("tr")
18
+ if not rows:
19
+ return "Error: No rows found in the tariff table."
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ # Parse table rows and extract data
22
+ tariff_data = []
23
+ for row in rows:
24
+ cells = row.find_all(["td", "th"]) # Include both header and data cells
25
+ tariff_data.append([cell.get_text(strip=True) for cell in cells])
26
+
27
+ # Return the tariff data as a list of lists (rows)
28
+ return tariff_data
29
 
 
30
  except Exception as e:
31
  return f"An error occurred while scraping: {e}"