Sure, I can help you build a contact details scraper tool using Python's Beautiful Soup library. Below is a step-by-step guide along with the complete code to scrape doctors' names, addresses, and consultation fees from the Practo Mumbai Psychologist page.
Disclaimer:
- Respect Website Policies: Before scraping, ensure that you have permission to scrape the website by reviewing its robots.txt and Terms of Service. Scraping without permission may violate their policies.
- Ethical Scraping: Use the scraper responsibly to avoid overloading the website's server. Consider adding delays between requests if scraping multiple pages.
- Legal Considerations: Ensure compliance with relevant laws and regulations regarding data scraping and usage.
Overview
We'll use the following Python libraries:
requests: To send HTTP requests to the website.
BeautifulSoup from bs4: To parse and navigate the HTML content.
csv: To save the scraped data into a CSV file for easy access and analysis.
Step-by-Step Guide
1. Install Required Libraries
First, ensure you have the necessary libraries installed. You can install them using pip if you haven't already:
pip install requests beautifulsoup4
2. Understand the HTML Structure
Based on the HTML snippet you provided, each doctor's details are encapsulated within a <div> with the attribute data-qa-id="doctor_card". Inside each card, the necessary information can be extracted as follows:
- Name: Located within an
<h2> tag with data-qa-id="doctor_name".
- Address: Composed of two
<span> tags with data-qa-id="practice_locality" and data-qa-id="practice_city".
- Consultation Fee: Located within a
<span> tag with data-qa-id="consultation_fee".
3. Complete Python Script
Here's the complete Python script to perform the scraping:
import requests
from bs4 import BeautifulSoup
import csv
import time
def scrape_practo_psychologists():
base_url = "https://www.practo.com/mumbai/psychologist"
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"
)
}
# Initialize a list to hold all doctor data
all_doctors = []
# Pagination handling (if applicable)
# Practo might use infinite scrolling or load more buttons.
# For simplicity, we'll handle the first page. To handle multiple pages,
# you might need to inspect API requests or use Selenium for dynamic content.
response = requests.get(base_url, headers=headers)
if response.status_code != 200:
print(f"Failed to retrieve the page. Status code: {response.status_code}")
return
soup = BeautifulSoup(response.content, "html.parser")
# Find all doctor cards
doctor_cards = soup.find_all("div", attrs={"data-qa-id": "doctor_card"})
if not doctor_cards:
print("No doctor cards found on this page.")
return
for index, card in enumerate(doctor_cards, start=1):
# Extract doctor's name
name_tag = card.find("h2", attrs={"data-qa-id": "doctor_name"})
name = name_tag.get_text(strip=True) if name_tag else "N/A"
# Extract address
locality_tag = card.find("span", attrs={"data-qa-id": "practice_locality"})
city_tag = card.find("span", attrs={"data-qa-id": "practice_city"})
locality = locality_tag.get_text(strip=True).rstrip(',') if locality_tag else ""
city = city_tag.get_text(strip=True) if city_tag else ""
address = f"{locality}, {city}" if locality and city else "N/A"
# Extract consultation fee
fee_tag = card.find("span", attrs={"data-qa-id": "consultation_fee"})
fee = fee_tag.get_text(strip=True) if fee_tag else "N/A"
# Append the data to the list
all_doctors.append({
"Name": name,
"Address": address,
"Consultation Fee": fee
})
print(f"Scraped {index}: {name}, {address}, {fee}")
# Save the data to a CSV file
csv_file = "practo_psychologists.csv"
try:
with open(csv_file, "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=["Name", "Address", "Consultation Fee"])
writer.writeheader()
writer.writerows(all_doctors)
print(f"\nSuccessfully saved data to {csv_file}")
except Exception as e:
print(f"Error writing to CSV file: {e}")
if __name__ == "__main__":
scrape_practo_psychologists()
4. Explanation of the Script
-
Import Libraries:
requests handles HTTP requests.
BeautifulSoup parses HTML content.
csv handles writing data to a CSV file.
time can be used for adding delays (not used in this basic script).
-
Set Headers:
- Setting a
User-Agent helps mimic a real browser, which can prevent the request from being blocked.
-
Send GET Request:
- The script sends a GET request to the specified URL.
- It checks if the request was successful (
status_code 200).
-
Parse HTML Content:
- The response content is parsed using Beautiful Soup with the
html.parser.
-
Find Doctor Cards:
- The script searches for all
<div> elements with data-qa-id="doctor_card", which contain individual doctor details.
-
Extract Required Information:
- Name: Extracted from the
<h2> tag with data-qa-id="doctor_name".
- Address: Combined from two
<span> tags with data-qa-id="practice_locality" and data-qa-id="practice_city".
- Consultation Fee: Extracted from the
<span> tag with data-qa-id="consultation_fee".
-
Store and Print Data:
- The extracted data is stored in a list of dictionaries.
- Each doctor's details are printed to the console for verification.
-
Save Data to CSV:
- The collected data is written to a CSV file named
practo_psychologists.csv.
5. Handling Multiple Pages (Optional)
Practo might use pagination to display multiple pages of doctors. To scrape multiple pages, you need to identify the pattern in the URL for different pages or inspect network requests to find APIs fetching the data. However, as websites frequently update their structures and use techniques like infinite scrolling, handling multiple pages might require more advanced techniques or tools like Selenium for rendering JavaScript.
6. Run the Script
Save the script to a file, e.g., scrape_practo.py, and run it using Python:
python scrape_practo.py
Upon successful execution, the script will print the scraped doctors' details and save them to practo_psychologists.csv.
7. Sample Output
Scraped 1: Dr. Naazneen Ladak, Andheri West, Mumbai, ₹2000
Scraped 2: Dr. Jane Doe, Bandra West, Mumbai, ₹2500
Scraped 3: Dr. John Smith, Juhu, Mumbai, ₹3000
...
Successfully saved data to practo_psychologists.csv
And the practo_psychologists.csv file will look like:
| Name | Address | Consultation Fee |
|---|
| Dr. Naazneen Ladak | Andheri West, Mumbai | ₹2000 |
| Dr. Jane Doe | Bandra West, Mumbai | ₹2500 |
| Dr. John Smith | Juhu, Mumbai | ₹3000 |
| ... | ... | ... |
Additional Tips
- Error Handling: Enhance the script by adding more robust error handling to manage unexpected HTML structures or missing data.
- Delays Between Requests: If you extend the script to handle multiple pages, consider adding delays (
time.sleep(seconds)) between requests to avoid overloading the server.
- Dynamic Content: If Practo loads content dynamically using JavaScript, consider using Selenium or other browser automation tools to render the page before scraping.
- Respect Rate Limits: Always respect the website's rate limits to avoid being blocked.
Feel free to customize and extend the script based on your specific requirements. Let me know if you need further assistance!