Python request.get error on wikipedia image url

Viewed 45
2 Answers

Most websites block requests that come in without a valid browser as a User-Agent. Wikimedia is one such.

import requests
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'}
res = requests.get('https://upload.wikimedia.org/wikipedia/commons/0/05/20100726_Kalamitsi_Beach_Ionian_Sea_Lefkada_island_Greece.jpg', headers=headers)
res.content

which will give you expected output

enter image description here

I typed ur code and it seems an " Error: 403, Forbidden. ". So what I can help with is Wikipedia requires a user agent header in the request.

import wikipedia
import requests
        
headers = {
    'User-Agent': 'My User Agent 1.0'
}

page = wikipedia.page("beach")
first_image_link = page.images[0]
req = requests.get(first_image_link, headers=headers, stream=True)
req.content

For the user agent, you should probably supply something a bit more descriptive than the placeholder I use in my example. Maybe the name of your script, or just the word "script" or something like that. I myself tested it and it works fine, you will get back the image as you are expecting.

Related