Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

python - Why switching to alert through selenium is not stable?

Why switching to alert through selenium is not stable?

For example.
1. Run a code and all good. Everything worked out well. But if this code is run in a few minutes, then there may be errors. There is no element you can click on, for example. And so on.
2. On one site there is an alert window.

alert = driver.switch_to_alert()
alert.dismiss()

So I close it. But he works through time. All is well, then errors.

for al in range(3):
    try:
        alert = driver.switch_to_alert()
        alert.dismiss()
        time.sleep(randint(1, 3))
    except:
        pass

I wrote and everything works out as it should.
But I think that this is not beautiful.
Why is everything so unstable?
Thank you very much.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As per your code block there are a couple of issues which you need to address as follows :

  • Switching to an Alert : The method switch_to_alert() is Deprecated and you should be using switch_to.alert instead. The API Docs clearly mentions the following :

     def switch_to_alert(self):
         """ Deprecated use driver.switch_to.alert
         """
         warnings.warn("use driver.switch_to.alert instead", DeprecationWarning)
         return self._switch_to.alert
    
  • Wait for the Alert to be present : You should always induce WebDriverWait for the Alert to be present before invoking accept() or dismiss() as follows :

    WebDriverWait(driver, 5).until(EC.alert_is_present).dismiss()
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...