I am attempting to write a Python script that retrieves the final redirect link of a Wikipedia page. For example, when accessing "http://en.wikipedia.org/wiki/Zzzzzz
", it should return "https://en.wikipedia.org/wiki/Z_(joke_line)
".
I have the following code that works for getting the redirect of any link and also works with the YouTube URL shortener, but it doesn't seem to work with Wikipedia links:
import requests
def get_final_url(url):
response = requests.get(url, allow_redirects=False)
if response.status_code in (300, 301, 302, 303, 307, 308):
return response.headers['Location']
else:
return None
initial_url = "http://en.wikipedia.org/wiki/Zzzzzz" # Replace with your URL
final_url = get_final_url(initial_url)
print("Final URL:", final_url)
http://en.wikipedia.org/wiki/Zzzzzz -> http://en.wikipedia.org/wiki/Zzzzzz
https://youtu.be/nMFv8YPOQdY -> https://www.youtube.com/watch?v=nMFv8YPOQdY&feature=youtu.be