NewToJS
NewToJS

Reputation: 2101

Selenium with Python: How to check if URL is valid

I have this functional test that gets a url from an href.

But how do I test test if it is valid (ie: 200/success and not 404)

def test_card_links(self):
    """Click card, make sure url is valid"""
    card_link = self.browser.find_element_by_css_selector('#app-scoop-panel a').get_attribute('href');

Upvotes: 1

Views: 1517

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193108

Once you retrieve the href attribute as card_link you can check the validity of the link using either of the following approaches:

  • Using requests.head():

    import requests
    
    def test_card_links(self):
        """Click card, make sure url is valid"""
        card_link = self.browser.find_element_by_css_selector('#app-scoop-panel a').get_attribute('href')
        request_response = requests.head(card_link)
        status_code = request_response.status_code
        if status_code == 200:
            print("URL is valid/up")
        else:
            print("URL is invalid/down")
    
  • Using urlopen():

    import requests
    import urllib
    
    def test_card_links(self):
        """Click card, make sure url is valid"""
        card_link = self.browser.find_element_by_css_selector('#app-scoop-panel a').get_attribute('href')
        status_code = urllib.request.urlopen(card_link).getcode()
        if status_code == 200:
            print("URL is valid/up")
        else:
            print("URL is invalid/down")
    

Upvotes: 1

Related Questions