close

[Solved] urllib2.HTTPError: HTTP Error 403: Forbidden

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error urllib2.HTTPError: HTTP Error 403: Forbidden in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How urllib2.HTTPError: HTTP Error 403: Forbidden Error Occurs?

Today I get the following error urllib2.HTTPError: HTTP Error 403: Forbidden in python.

How To Solve urllib2.HTTPError: HTTP Error 403: Forbidden Error ?

  1. How To Solve urllib2.HTTPError: HTTP Error 403: Forbidden Error ?

    To Solve urllib2.HTTPError: HTTP Error 403: Forbidden Error Actually, it works with just this one additional header:
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',

  2. urllib2.HTTPError: HTTP Error 403: Forbidden

    To Solve urllib2.HTTPError: HTTP Error 403: Forbidden Error Actually, it works with just this one additional header:
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',

Solution 1

This will work in Python 3

import urllib.request
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
url = "http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers"
headers={'User-Agent':user_agent,} 
request=urllib.request.Request(url,None,headers) #The assembled request
response = urllib.request.urlopen(request)
data = response.read() # The data u need

Solution 2

By adding a few more headers I was able to get the data:

import urllib2,cookielib
site= "http://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/getHistoricalData.jsp?symbol=JPASSOCIAT&fromDate=1-JAN-2012&toDate=1-AUG-2012&datePeriod=unselected&hiddDwnld=true"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
       'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
       'Accept-Encoding': 'none',
       'Accept-Language': 'en-US,en;q=0.8',
       'Connection': 'keep-alive'}
req = urllib2.Request(site, headers=hdr)
try:
    page = urllib2.urlopen(req)
except urllib2.HTTPError, e:
    print e.fp.read()
content = page.read()
print content

Actually, it works with just this one additional header:

'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read