通过 webdriver 点击 javascript 弹出窗口

2023-07-04Python开发问题
19

本文介绍了通过 webdriver 点击 javascript 弹出窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在 Python 中使用 Selenium 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.

它会生成一个弹出窗口(Javascript Alert).我不确定,如何通过 webdriver 点击弹出窗口.

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

知道怎么做吗?

谢谢

推荐答案

Python Webdriver 脚本:

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()

网页(alert.html):

Webpage (alert.html):

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

运行 webdriver 脚本将打开显示警报的 HTML 页面.Webdriver 立即切换到警报并接受它.Webdriver 然后关闭浏览器并结束.

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()

如果需要查看alert的文本,可以通过访问alert对象的text属性来获取alert的文本:

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()

这篇关于通过 webdriver 点击 javascript 弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11