Modify this to save the data after every loop initially only, so that if the software breaks somewhere in between then still the extracted data is saved. And also for a particular search its just got stuck in a loop, and its incrementing page number and getting the same data that was on initial page url, so find the total page numbers in the start only if possible, or some other solution to not get stuck in such a loop -
import requests
from bs4 import BeautifulSoup
import csv
import time
all_doctors = []
for city in cities:
for designation in designations:
base_url = f"https://www.practo.com/{city}/{designation}"
page = 1 # Start from the first page
while True:
# Construct the URL for the current page
if page == 1:
url = base_url
else:
url = f"{base_url}?page={page}"
print(f"Scraping Page {page}: {url}")
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Request failed for page {page}: {e}")
break
soup = BeautifulSoup(response.content, "html.parser")
# Find all doctor cards on the current page
doctor_divs = soup.find_all("div", class_="u-border-general--bottom")
# If no doctor cards are found, assume we've reached the last page
if not doctor_divs:
print(f"No doctor entries found on page {page}. Ending scraping for {designation} in {city}.")
break
# Iterate through each doctor card and extract details
for div in doctor_divs:
# Extract doctor's name
name_tag = div.find("h2", attrs={"data-qa-id": "doctor_name"})
name = name_tag.get_text(strip=True) if name_tag else None
# Extract address
locality_tag = div.find("span", attrs={"data-qa-id": "practice_locality"})
city_tag = div.find("span", attrs={"data-qa-id": "practice_city"})
locality = locality_tag.get_text(strip=True).rstrip(',') if locality_tag else ""
city_name = city_tag.get_text(strip=True) if city_tag else ""
address = f"{locality}, {city_name}" if locality and city_name else None
# Extract consultation fee
fee_tag = div.find("span", attrs={"data-qa-id": "consultation_fee"})
fee = fee_tag.get_text(strip=True).replace('₹', '').replace(',', '') if fee_tag else None
# Check for mandatory fields
if name and address and fee:
try:
fee = int(fee) # Convert fee to integer for consistency
except ValueError:
fee = None
# Only append if all required fields are present and valid
if name and address and fee:
doctor_info = {
"Name": name,
"Address": address,
"Consultation Fee": fee,
"City": city_name,
"Designation": designation
}
all_doctors.append(doctor_info)
print(f"Scraped Doctor {len(all_doctors)}: {name}, {address}, ₹{fee}")
else:
print(f"Skipped a doctor entry due to missing information.")
# Move to the next page
page += 1
time.sleep(1) # Delay to be polite and avoid overloading the server
# Define CSV file name
csv_file = "practo_doctors.csv"
# Define CSV headers
fieldnames = ["Name", "Address", "Consultation Fee", "City", "Designation"]
try:
with open(csv_file, "w", newline='', encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(all_doctors)
print(f"\nSuccessfully saved {len(all_doctors)} records to {csv_file}")
except Exception as e:
print(f"Error writing to CSV file: {e}")
Certainly! To enhance the robustness and reliability of your scraping script, we'll implement the following modifications:
Incremental Data Saving:
Instead of accumulating all data in memory and writing it to a CSV file only at the end, we'll write each doctor's information to the CSV file immediately after it's scraped. This ensures that even if the script encounters an error or stops unexpectedly, all previously scraped data remains saved.
Preventing Infinite Loops by Determining Total Pages:
We'll extract the total number of pages from the pagination section of the first page for each city and designation. This allows the scraper to know exactly how many pages to iterate through, preventing it from getting stuck in an infinite loop. If the total number of pages isn't available or if there's an unexpected structure, we'll also implement a safety mechanism to stop after a reasonable number of pages.
Below is the modified script with detailed comments explaining each change:
python
import requests
from bs4 import BeautifulSoup
import csv
import time
import os
def scrape_practo_psychologists(cities, designations):
headers = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/58.0.3029.110 Safari/537.3"
)
}
# Define CSV file name
csv_file = "practo_doctors.csv"
file_exists = os.path.isfile(csv_file)
# Define CSV headers
fieldnames = ["Name", "Address", "Consultation Fee", "City", "Designation"]
try:
# Open the CSV file in append mode
with open(csv_file, "a", newline='', encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
# Write headers only if the file doesn't exist
if not file_exists:
writer.writeheader()
for city in cities:
for designation in designations:
base_url = f"https://www.practo.com/{city}/{designation}"
print(f"\nStarting scraping for {designation} in {city}.")
# Initialize variables to determine total pages
total_pages = None
try:
response = requests.get(base_url, headers=headers, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.content, "html.parser")
# Attempt to find pagination section
pagination = soup.find("div", class_="pagination")
if pagination:
page_links = pagination.find_all("a", href=True)
page_numbers = []
for link in page_links:
try:
num = int(link.get_text())
page_numbers.append(num)
except ValueError:
continue
if page_numbers:
total_pages = max(page_numbers)
else:
# If no pagination found, assume single page
total_pages = 1
except requests.exceptions.RequestException as e:
print(f"Failed to retrieve the first page for {designation} in {city}: {e}")
continue # Skip to the next designation/city
if not total_pages:
total_pages = 1 # Fallback to single page if unable to determine
print(f"Total pages to scrape for {designation} in {city}: {total_pages}")
for page in range(1, total_pages + 1):
# Construct the URL for the current page
if page == 1:
url = base_url
else:
url = f"{base_url}?page={page}"
print(f"Scraping Page {page}: {url}")
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Request failed for page {page} ({url}): {e}")
break # Exit the loop for this designation/city
soup = BeautifulSoup(response.content, "html.parser")
# Find all doctor cards on the current page
doctor_divs = soup.find_all("div", class_="u-border-general--bottom")
# If no doctor cards are found, assume we've reached the last page
if not doctor_divs:
print(f"No doctor entries found on page {page}. Ending scraping for {designation} in {city}.")
break
# Iterate through each doctor card and extract details
for div in doctor_divs:
# Extract doctor's name
name_tag = div.find("h2", attrs={"data-qa-id": "doctor_name"})
name = name_tag.get_text(strip=True) if name_tag else None
# Extract address
locality_tag = div.find("span", attrs={"data-qa-id": "practice_locality"})
city_tag = div.find("span", attrs={"data-qa-id": "practice_city"})
locality = locality_tag.get_text(strip=True).rstrip(',') if locality_tag else ""
city_name = city_tag.get_text(strip=True) if city_tag else ""
address = f"{locality}, {city_name}" if locality and city_name else None
# Extract consultation fee
fee_tag = div.find("span", attrs={"data-qa-id": "consultation_fee"})
fee = fee_tag.get_text(strip=True).replace('₹', '').replace(',', '') if fee_tag else None
# Check for mandatory fields
if name and address and fee:
try:
fee = int(fee) # Convert fee to integer for consistency
except ValueError:
fee = None
# Only append and write if all required fields are present and valid
if name and address and fee:
doctor_info = {
"Name": name,
"Address": address,
"Consultation Fee": fee,
"City": city_name,
"Designation": designation
}
writer.writerow(doctor_info)
print(f"Scraped Doctor: {name}, {address}, ₹{fee}")
else:
print(f"Skipped a doctor entry due to missing information.")
# Delay to be polite and avoid overloading the server
time.sleep(1)
print(f"\nScraping completed. Data has been saved to {csv_file}")
except Exception as e:
print(f"An error occurred during scraping: {e}")
if __name__ == "__main__":
cities = ["mumbai", "bangalore", "delhi", "chennai", "hyderabad", "kolkata", "gurgaon", "gurugram", "chandigadh", "mohali"]
designations = ["psychiatrist", "psychologist", "neurologist"]
scrape_practo_psychologists(cities, designations)
Detailed Explanation of the Modifications
Incremental Data Saving:
Appending to CSV Instead of Accumulating in Memory:
Before: The script accumulated all scraped doctor information in the all_doctors list and wrote them to the CSV file at the end.
After: The script opens the CSV file in append mode ("a") and writes each doctor's information as soon as it's scraped using writer.writerow(doctor_info). This ensures that data is saved incrementally.
Handling CSV Headers:
To prevent rewriting headers each time the script runs or appends data, the script checks if the CSV file already exists using os.path.isfile(csv_file). If the file doesn't exist, it writes the headers; otherwise, it skips writing headers.
Preventing Infinite Loops by Determining Total Pages:
Extracting Total Number of Pages:
The script attempts to determine the total number of pages by locating the pagination section on the first page.
It looks for a div with the class pagination and extracts all page numbers from the pagination links.
The highest page number found is considered the total number of pages to scrape.
Handling Cases Where Pagination is Not Found:
If the pagination section isn't found or if no page numbers can be extracted, the script defaults to scraping only the first page to prevent infinite looping.
Iterating Through Determined Pages:
Using the determined total_pages, the script iterates from page 1 to total_pages, constructing the appropriate URL for each page and scraping the data accordingly.
Safety Mechanism:
Even with pagination, there's a possibility of unexpected website structures or changes. As a safety measure, if the script encounters an error while determining the total number of pages or during scraping, it gracefully moves on to the next city/designation without getting stuck.
Additional Enhancements:
Improved Logging:
The script provides clear console output indicating the progress, such as which city and designation are being scraped, the total number of pages, and the status of each doctor scraped or skipped.
By implementing these modifications, your scraping script becomes more resilient, efficient, and reliable, ensuring that you capture as much data as possible without unnecessary interruptions or data loss.
Not yet included in a published release.
Error Handling:
Comprehensive try-except blocks ensure that any network-related issues or unexpected errors don't crash the entire script. Instead, they provide informative messages and continue with the next iteration.
Politeness Delay:
A time.sleep(1) call ensures that the scraper waits for 1 second between page requests, reducing the load on the server and minimizing the risk of being blocked.
Usage Notes:
Duplicate Entries:
Since the script appends data to the CSV file, running it multiple times without clearing the CSV might result in duplicate entries. Ensure that you handle duplicates if necessary.
Dynamic Website Structures:
Websites often change their HTML structures. If the script stops working, you might need to inspect the website and update the parsing logic accordingly.
Respect Website's Terms of Service:
Ensure that you have permission to scrape the website and that you're complying with its terms of service.