A quick guide and code example on how to verify URL redirects by launching a real browser using Python and Selenium.
Firstly we’ll import webdriver, and the ‘time’ module (we’ll use that in a bit):
from selenium import webdriver
import time
Then we create a dictionary containing the target and redirect destination URLs:
urls = {
"https://www.targeturl.com" : "https://www.destinationurl.com",
"https://www.targeturl.com" : "https://www.destinationurl.com",
"https://www.targeturl.com" : "https://www.destinationurl.com",
}
Specify our web driver (using safari for ease, as web driver built-in):
driver = webdriver.Safari()
Now we’ll iterate through each url in our dictionary:
for target, destination in urls.items():
driver.get(target)
And allow 1 second before grabbing whatever URL we have arrived at in the address bar and saving into a new variable called ‘current_url’:
for target, destination in urls.items():
driver.get(target)
time.sleep(1)
current_url = driver.current_url
Then we’ll compare where we’ve ended up with what we expect from our dictionary:
for target, destination in urls.items():
driver.get(target)
time.sleep(1)
current_url = driver.current_url
if current_url == destination:
print(' - Redirect success')
else:
error = f'> Redirect error: {target} redirected to {current_url}, should have redirected to {destination}'
Putting it all together
from selenium import webdriver
import time
urls = {
"https://www.targeturl.com" : "https://www.destinationurl.com",
"https://www.targeturl.com" : "https://www.destinationurl.com",
"https://www.targeturl.com" : "https://www.destinationurl.com",
}
driver = webdriver.Safari()
for target, destination in urls.items():
driver.get(target)
time.sleep(1)
current_url = driver.current_url
if current_url == destination:
print(' - Redirect success')
else:
error = f'> Redirect error: {target} redirected to {current_url}, should have redirected to {destination}'
driver.close()