0

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
InSync
  • 4,851
  • 4
  • 8
  • 30
  • I tried to see how that Zzzzzz url ended at https://en.wikipedia.org/wiki/Z_(joke_line), and the only reference to it was in the body content. This answer seems to suggest the same approach: https://stackoverflow.com/a/47537837/190902 – hookedonwinter Jun 16 '23 at 16:23
  • Does this answer your question? [Python - How to get the page Wikipedia will redirect me to?](https://stackoverflow.com/questions/47537644/python-how-to-get-the-page-wikipedia-will-redirect-me-to) – logi-kal Jun 24 '23 at 07:20

1 Answers1

0

Here is what ended up working for me:

import requests, json

def get_final_url(name):
    url = f'https://en.wikipedia.org/w/api.php?action=query&titles={name}&redirects&format=json'
    response = requests.get(url)
    return json.loads(response.text)["query"]["redirects"][0]["to"]

initial_url = "Zzzzzz"  # Replace with your URL
final_url = get_final_url(initial_url)
print(final_url)
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 17 '23 at 21:30