如何在Selenium 2python中捕获弹出窗口

2024-04-24 00:20:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我今晚刚开始使用Selenium 2,所以这将是非常基本的(我希望…)。在

我正试图登录我在http://contentparadise.com/的帐户

我进入登录页面https://www.contentparadise.com/signin.aspx,可以输入id/pw,然后提交。但是即使有了正确的id/pw,它也会将我返回到登录页面-在一个小的消息框中添加了“发生了以下错误”。很明显,代码中的id/pw是错误的,我试图将其检测为一个错误-但是即使使用我的真实id/pw我也能理解。在

如何检测和读取此messagebox,以及为什么正确的设置不转到主页?在

我在另一个站点上使用了相同的代码,使用了正确的设置,它会将我带到主页。在

这是使用javascript的登录页面吗?如果您查看登录页的源代码,请查找字符串“”以开始该部分表单。在

代码如下:

from selenium import webdriver
import sys
import os

userID = "wajahbaru"
pw = "marmalade"

wdrv = webdriver.Firefox()
wdrv.get("https://www.contentparadise.com/signin.aspx")

print "Page #1 title is: " + wdrv.title; # should be "Sign In"

unamefield = wdrv.find_element_by_name("ctl00$ContentPlaceHolder1$txtUserName").send_keys(userID)
pwdfield = wdrv.find_element_by_name("ctl00$ContentPlaceHolder1$txtPassword").send_keys(pw)
pwdfield = wdrv.find_element_by_name("ctl00$ContentPlaceHolder1$btnLogin").click()

print "Page #2 title is: " + wdrv.title; # if logged in this should be "Content Paradise: Buy or Sell Software, 2D Content, 3D Models and Audio."

wdrv.get_screenshot_as_file("test.jpg")
wdrv.quit()

Tags: 代码nameimportcomidbytitle错误
2条回答

How do I detect and read this messagebox, and why doesn't the correct set go to the home page?

要检测错误消息框,可以使用id="error"搜索元素:

#!/usr/bin/env python
from contextlib import closing
from selenium.webdriver import Firefox as Browser
from selenium.webdriver.support.ui import WebDriverWait

timeout = 10 # seconds

with closing(Browser()) as browser:
    browser.get('https://www.contentparadise.com/signin.aspx')
    assert browser.title == "Sign In"
    login, password, submit = map(browser.find_element_by_id,
        ['ctl00_ContentPlaceHolder1_txtUserName',
         'ctl00_ContentPlaceHolder1_txtPassword',
         'ctl00_ContentPlaceHolder1_btnLogin'])
    enter_text = lambda x, text: (x.clear(), x.send_keys(text))
    enter_text(login, "abc")
    enter_text(password, "pas$W0rd")
    submit.click()

    # wait for error or success
    value = WebDriverWait(browser, timeout).until(
        lambda x: ("Content Paradise" in x.title and "ok" or
                   x.find_element_by_id('error')))
    if value != "ok":
       print "error:", value.text
    browser.get_screenshot_as_file('test.jpg')

在下面的链接中搜索“弹出对话框”。。如果你想了解更多,搜索你在谷歌找到的代码,你会得到一些好东西;-)

http://readthedocs.org/docs/selenium-python/en/latest/navigating.html?highlight=popup

相关问题 更多 >