pythonpython-3.xbeautifulsoupbs4dash

HTTP 403 forbidden is showing while scraping a data from a website using python and bs4


when 403 forbidden error is showing while scrapping a data then how to proceed further and scrape a data from a website

how to scrape a data please guide me i am a beginner for web scrapping

import requests, bs4
from bs4 import BeautifulSoup
from csv import writer
url = "https://www.zocdoc.com/gastroenterologists/2"
page = requests.get(url)
page
page.status_code
**403**
page.content
soup = BeautifulSoup(page.content, 'html.parser')
soup
print(soup.prettify())
users = soup.find_all('div', {'data-test': 'search-content'})
 for use in users:
   doctor = use.find('span', attrs={'data-test': 'doctor-card-info-name-full'})#.replace('\n', '')
   specialty = list.find('div', {'data-test': 'doctor-card-info-specialty'})
   #specialty = list.find('div', class_="sc-192nc1l-0 buuGUI overflown")#.text.replace('\n', '')
   #price = list.find('div', class_="listing-search-item__price").text.replace('\n', '')
   #area = list.find('div', class_="listing-search-item__features").text.replace('\n', '')
   info = [doctor] #price, area]
   print(info)

not getting an output also, in this website is not having a section tag to fetch or finding all data


Solution

  • You can overcome the 403 error in this case by:

    import requests
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:96.0) Gecko/20100101 Firefox/96.0'}
    HOST = 'https://www.zocdoc.com'
    PAGE = 'gastroenterologists/2'
    with requests.Session() as session:
        (r := session.get(HOST, headers=headers)).raise_for_status()
        (r := session.get(f'{HOST}/{PAGE}', headers=headers)).raise_for_status()
        # process content from here