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
140 views
in Technique[技术] by (71.8m points)

python - Click the javascript popup through webdriver

I am scraping a webpage using Selenium webdriver in Python

The webpage I am working on, has a form. I am able to fill the form and then I click on the Submit button.

It generates an popup window( Javascript Alert). I am not sure, how to click the popup through webdriver.

Any idea how to do it ?

Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Python Webdriver Script:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://sandbox.dev/alert.html")
alert = browser.switch_to_alert()
alert.accept()
browser.close()

Webpage (alert.html):

<html><body>
    <script>alert("hey");</script>
</body></html>

Running the webdriver script will open the HTML page that shows an alert. Webdriver immediately switches to the alert and accepts it. Webdriver then closes the browser and ends.

If you are not sure there will be an alert then you need to catch the error with something like this.

from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://sandbox.dev/no-alert.html")

try:
    alert = browser.switch_to_alert()
    alert.accept()
except:
    print "no alert to accept"
browser.close()

If you need to check the text of the alert, you can get the text of the alert by accessing the text attribute of the alert object:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://sandbox.dev/alert.html")

try:
    alert = browser.switch_to_alert()
    print alert.text
    alert.accept()
except:
    print "no alert to accept"
browser.close()

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

...