Engineer786 commited on
Commit
473a876
·
verified ·
1 Parent(s): a2d8555

Rename scraper.py to tariff_scraper.py

Browse files
Files changed (2) hide show
  1. scraper.py +0 -69
  2. tariff_scraper.py +57 -0
scraper.py DELETED
@@ -1,69 +0,0 @@
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 ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from bs4 import BeautifulSoup
3
+
4
+ # Define the URL for PESCO tariff rates
5
+ TARIFF_URLS = {
6
+ "PESCO": "https://onlinepescobill.pk/pesco-tariff-rates/"
7
+ }
8
+
9
+ def scrape_tariff_data(url):
10
+ """
11
+ Scrape tariff data from the given URL.
12
+
13
+ Args:
14
+ url (str): The URL of the tariff page to scrape.
15
+
16
+ Returns:
17
+ list: A list of strings representing the rows of tariff data.
18
+ """
19
+ try:
20
+ # Send an HTTP GET request to the specified URL
21
+ response = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
22
+ response.raise_for_status() # Raise an error for HTTP issues
23
+
24
+ # Parse the webpage content using BeautifulSoup
25
+ soup = BeautifulSoup(response.text, 'html.parser')
26
+
27
+ # Extract table rows
28
+ tariff_table = soup.find('table')
29
+ if not tariff_table:
30
+ return ["No table found on the webpage."]
31
+
32
+ data = []
33
+ table_rows = tariff_table.find_all('tr')
34
+ for row in table_rows:
35
+ # Extract text from each <td> or <th> within the row
36
+ row_text = ' | '.join(
37
+ col.get_text(strip=True) for col in row.find_all(['th', 'td'])
38
+ )
39
+ if row_text: # Add only rows that have meaningful data
40
+ data.append(row_text)
41
+
42
+ return data if data else ["No data found in the table."]
43
+ except requests.exceptions.RequestException as e:
44
+ # Handle request errors (e.g., connection issues, timeout)
45
+ return [f"Request error: {e}"]
46
+ except Exception as e:
47
+ # Handle other potential errors
48
+ return [f"An unexpected error occurred: {e}"]
49
+
50
+ if __name__ == "__main__":
51
+ # Test the scraper
52
+ url = TARIFF_URLS["PESCO"]
53
+ print(f"Fetching tariff data from {url}...\n")
54
+ tariff_data = scrape_tariff_data(url)
55
+ print("Tariff Data:")
56
+ for row in tariff_data:
57
+ print(row)