Search code examples
pythonpython-requestsurlopen

Web scraping using python: urlopen returns HTTP Error 403: Forbidden


I'm trying to download data from Fragantica.com using urlopen but an error occurs ("HTTP Error 403: Forbidden") even after changing the user-agent and adding headers. I have tried the code from here as well with no success (http://wolfprojects.altervista.org/changeua.php#problem).

Here is my code:

import urllib.request

user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Safari/605.1.15'



url = "https://www.fragrantica.com/perfume/Tom-Ford/Tobacco-Vanille-1825.html"
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

This is the error I encounter: HTTPError: HTTP Error 403: Forbidden


Solution

  • You might need to specify more headers, try this:

    import urllib.request    
    
    url = "https://www.fragrantica.com/perfume/Tom-Ford/Tobacco-Vanille-1825.html"
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.4 Safari/605.1.15',
           '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'} 
    
    request=urllib.request.Request(url=url, headers=headers) #The assembled request
    response = urllib.request.urlopen(request)
    data = response.read() # The data u need