Engineer786 commited on
Commit
2b4aa81
·
verified ·
1 Parent(s): 31e2234

Update tariff_scraper.py

Browse files
Files changed (1) hide show
  1. tariff_scraper.py +31 -17
tariff_scraper.py CHANGED
@@ -1,25 +1,39 @@
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')
17
- for row in table_rows:
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}"
 
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 data from the IESCO tariff guide page.
7
+
8
+ Parameters:
9
+ url (str): The URL of the tariff data page.
10
+ Defaults to the IESCO Tariff Guide page.
11
+
12
+ Returns:
13
+ list: A list of rows containing tariff-related data as strings.
14
+ str: Error message if scraping fails.
15
+ """
16
  try:
17
+ response = requests.get(url)
18
+ response.raise_for_status() # Raise error for bad responses
19
  soup = BeautifulSoup(response.text, 'html.parser')
20
+
21
+ # Assuming the tariff data is stored in table rows
22
+ table = soup.find("table") # Locate the main table
23
+ if not table:
24
+ return "No table found on the page. Please verify the URL."
25
+
26
+ table_rows = table.find_all("tr") # Extract all table rows
27
+ scraped_data = []
28
 
29
+ for row in table_rows:
30
+ row_data = [cell.get_text(strip=True) for cell in row.find_all(["th", "td"])]
31
+ if row_data: # Only add rows with data
32
+ scraped_data.append(" | ".join(row_data))
33
+
34
+ if not scraped_data:
35
+ return "No tariff data found in the table. Please check the page structure."
36
 
37
+ return scraped_data
 
 
 
 
 
 
 
 
 
 
38
  except Exception as e:
39
+ return f"An error occurred while scraping: {e}"