How to detect when Selenium loads a browser's error page

南楼画角 提交于 2019-11-30 08:37:49

问题


Is there a universal way to detect when a selenium browser opens an error page? For example, disable your internet connection and do

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

In Firefox, Selenium will load the 'Try Again' error page containing text like "Firefox can't establish a connection to the server at www.google.com." Selenium will NOT throw any errors.

Is there a browser-independent way to detect these cases? For firefox (python), I can do

if "errorPageContainer" in [ elem.get_attribute("id") for elem in driver.find_elements_by_css_selector("body > div") ]

But (1) this seems like computational overkill (see next point below) and (2) I must create custom code for every browser.

If you disable your internet and use htmlunit as the browser you will get a page with the following html

<html>
    <head></head>
    <body>Unknown host</body>
</html>

How can I detect this without doing

if driver.find_element_by_css_selector("body").text == "Unknown host"

It seems like this would be very expensive to check on every single page load since there would usually be a ton of text in the body.

Bonus points if you also know of a way to detect the type of load problem, for example no internet connection, unreachable host, etc.


回答1:


WebDriver API doesnot expose HTTP status codes , so if you want to detect/manage HTTP errors, you should use a debugging proxy.

See Jim's excellent post Implementing WebDriver HTTP Status on how to do exactly that.




回答2:


If you just need to remote-control the Tor Browser, you might also consider the Marionette framework by Mozilla. Bonus: It fails when a page cannot be loaded: (see navigate(url) in the API)

The command will return with a failure if there is an error loading the document or the URL is blocked. This can occur if it fails to reach the host, the URL is malformed, the page is restricted (about:* pages), or if there is a certificate issue to name some examples.

Example use (copy from other answer):

To use with the Tor Browser, enable marionette at startup via

Browser/firefox -marionette

(inside the bundle). Then, you can connect via

from marionette import Marionette
client = Marionette('localhost', port=2828);
client.start_session()

and load a new page for example via

url='http://mozilla.org'
client.navigate(url);

For more examples, there is a tutorial.



来源:https://stackoverflow.com/questions/22740778/how-to-detect-when-selenium-loads-a-browsers-error-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!