带有 Python 的 Selenium:如何检查 URL 是否有效

Selenium with Python: How to check if URL is valid

我有这个功能测试,它从 href 中获取 url。

但是我该如何测试它是否有效(即:200/成功而不是 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');

href 属性检索为 card_link 后,您可以检查 link 使用以下任一方法:

  • 使用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")
    
  • 使用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")