How to get status code by using selenium.py (python code)

前端 未结 12 1105
深忆病人
深忆病人 2020-11-30 01:01

I am writing a selenium script by python, but I think I don\'t see any information about:

How to get http status code from selenium Python code.

12条回答
  •  独厮守ぢ
    2020-11-30 01:47

    I will refer you to a question I asked earlier: How to detect when Selenium loads a browser's error page

    The short of it is that unless you want to get uber fancy with something like a squid proxy or browsermob, then you have to go for a dirty solution like below.

    Replace

    driver.get( "http://google.com" )
    

    with

    def goTo( url ):
        if "errorPageContainer" in [ elem.get_attribute("id") for elem in driver.find_elements_by_css_selector("body > div") ]:
            raise Exception( "this page is an error" )
        else:
            driver.get( url )
    

    You can get creative and get the error code based on the text displayed in the actual browser. This will have to be customized based on the browser; the one above works for firefox.

    The only way this becomes problematic is with 404's (page not found), since many sites have their own error pages and you have to customize it for each one.

提交回复
热议问题