To address the issues you've encountered with your scraping function, I'll provide an optimized version that:
-
Fixes the Encoding Error: The error charmap codec can't encode character \u20b9 occurs because the default encoding in your environment doesn't support certain Unicode characters (like the Indian Rupee symbol ₹). By explicitly setting the encoding to utf-8 when opening the CSV file, we can resolve this.
-
Eliminates Entries with 'N/A': To ensure that entries with 'N/A' values are excluded from the final CSV, we'll add checks before appending the doctor data to the all_doctors list.
-
Optimizes CSV Writing: We'll remove redundant file opening and ensure that the CSV is written efficiently.
-
Enhances Error Handling and Logging: Adding more descriptive logs and handling potential exceptions will make the function more robust.
-
Includes Necessary Imports: Ensure all required modules are imported.
Here's the revised and optimized function:
import requests
from bs4 import BeautifulSoup
import csv
import time
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"
)
}
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}")
Key Improvements Explained
-
Encoding Fix:
- Issue: The error encountered was due to characters that couldn't be encoded with the default encoding.
- Solution: Set
encoding="utf-8" in the open function to handle all Unicode characters properly.
-
Avoiding 'N/A' Entries:
- Implementation: Instead of assigning "N/A" to missing fields, the function sets
None and checks if essential fields (name, address, fee) are present before appending to all_doctors.
- Benefit: Only complete and valid entries are saved, ensuring the final CSV doesn't contain incomplete data.
-
Enhanced Fee Extraction:
- Improvement: Removed the Rupee symbol and commas from the fee string and attempted to convert it to an integer for consistency.
-
Error Handling:
- Requests: Added a
try-except block around the requests.get call to handle network issues gracefully.
- CSV Writing: Wrapped the CSV writing process in a
try-except block to catch and report any issues during file operations.
-
Logging and Feedback:
- Print Statements: Enhanced logging to provide clear feedback on what's being scraped, skipped, or if any errors occur.
-
Optimized CSV Writing:
- Removal of Redundant File Opening: Removed the unnecessary
file = open(csv_file, "w") line since the file is properly handled within the with statement.
- Field Names Consistency: Ensured that the field names used in the
DictWriter match the keys in the doctor_info dictionary.
-
Imports:
- Included Necessary Imports: Made sure that
requests, BeautifulSoup from bs4, csv, and time are imported at the beginning of the script.
Usage Example
To use the function, ensure you pass lists of cities and designations. For example:
cities = ["new-delhi", "mumbai", "bangalore"]
designations = ["psychologist", "therapist"]
scrape_practo_psychologists(cities, designations)
This will scrape psychologists and therapists from Practo in New Delhi, Mumbai, and Bangalore, saving the results to practo_doctors.csv.
Additional Recommendations
- Respect Robots.txt: Always check the website’s
robots.txt file to ensure you're allowed to scrape the content.
- Rate Limiting: Although a
time.sleep(1) is included, consider increasing the delay or implementing more sophisticated rate limiting to avoid being blocked.
- Proxy Usage: For large scraping tasks, using proxies can help distribute the requests and reduce the risk of being blocked.
- Dynamic Content Handling: If the website uses JavaScript to load content dynamically, consider using tools like Selenium or Playwright.
Feel free to further customize the function based on your specific requirements and ensure compliance with legal and ethical guidelines when scraping websites.