通过selenium IDE正确启动网址,但不通过脚本

时间:2017-10-12 07:29:41

标签: python python-2.7 selenium selenium-webdriver geckodriver

我正在尝试启动一个曾经加载的网址会提示输入用户名和密码。

问题是,当我通过selenium IDE录制和运行测试用例时,它可以工作。 但是,当我尝试通过代码启动URL时,它变为灰色,并且不显示任何用户名和密码的提示

观察:

当我手动打开网址时

url =http://10.131.14.245:30016/index.html

它会在几秒钟后自动重定向到

http://10.131.14.245:30016/index.html#/Login

,用户名和密码的提示看起来可见。

但是在脚本执行期间,URL不会重定向自身,而且仍然是

url =http://10.131.14.245:30016/index.html

即使我们通过代码添加值'#Login',它也不起作用

我正在使用 Python 2.7 硒3.6 Firefox 52.4 geckodriver v.018

下面是geckodriver.log文件中的错误

1507793622480   geckodriver INFO    geckodriver 0.18.0
1507793622495   geckodriver INFO    Listening on 127.0.0.1:56485
1507793624523   geckodriver::marionette INFO    Starting browser C:\Program Files\Mozilla Firefox\firefox.exe with args ["-marionette"]
1507793626284   Marionette  INFO    Listening on port 56493
1507793626626   Marionette  WARN    TLS certificate errors will be ignored for this session
JavaScript warning: http://10.131.14.245:30016/vendor/jquery/jquery.min.js, line 1: Using //@ to indicate sourceMappingURL pragmas is deprecated. Use //# instead
JavaScript error: http://10.131.14.245:30016/vendor/requirejs/require.js, line 165: Error: Load timeout for modules: angular,ocLazyLoad,angular-ui-router,angular-translate,angular-sanitize,angular-translate-loader-static-files,angular-translate-loader-partial,angular-css-injector
http://requirejs.org/docs/errors.html#timeout
#timeout
1507793619059   addons.productaddons    WARN    Failed downloading via XHR, status: 0, reason: error
1507793619078   addons.productaddons    WARN    Failed downloading via XHR, status: 0, reason: error
[Child 12096] WARNING: pipe error: 109: file c:/builds/moz2_slave/m-esr52-w64-000000000000000000/build/src/ipc/chromium/src/chrome/common/ipc_channel_win.cc, line 345

下面是python中的错误

D:\userdata\khchoudh\Desktop\POC\Selenium Robotframework\Firefox>python worked2.py
EE
======================================================================
ERROR: test_worked2 (__main__.Worked2)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "worked2.py", line 21, in test_worked2
    driver.find_element_by_name("username").clear()
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 437, in find_element_by_name
    return self.find_element(by=By.NAME, value=name)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 843, in find_element
    'value': value})['value']
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: Unable to locate element: [name="username"]

Python代码

- - 编码:utf-8 - -

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re

class Worked2(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "http://10.131.14.245:30016/index.html"
        self.verificationErrors = []
        self.accept_next_alert = True

    def test_worked2(self):
        driver = self.driver
        driver.get(self.base_url + "#/login")
        driver.find_element_by_name("username").clear()
        driver.find_element_by_name("username").send_keys("xxxx")
        driver.find_element_by_name("password").clear()
        driver.find_element_by_name("password").send_keys("xxxx")
        driver.find_element_by_xpath("//button").click()

    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException as e: return False
        return True

    def is_alert_present(self):
        try: self.driver.switch_to_alert()
        except NoAlertPresentException as e: return False
        return True

    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally: self.accept_next_alert = True

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

网站的HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title ng-bind="title">OpenDayLight DLUX</title>

    <meta name="description" content="overview &amp; stats" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script type="text/javascript">
var module = ['angular','ocLazyLoad','angular-ui-router','angular-translate', 'angular-sanitize', 'angular-translate-loader-static-files', 'angular-translate-loader-partial', 'angular-css-injector'];
var deps = ['common/config/env.module','app/testsetup/testsetup.module','app/core/core.module','app/designboard/designboard.module','app/testautomation/testautomation.module','common/login/login.module','common/authentification/auth.module','common/navigation/navigation.module','common/topbar/topbar.module','common/general/common.general.module','app/topology/topology.module','app/yangui/main','common/yangutils/yangutils.module','common/sigmatopology/sigmatopology.module','app/yangvisualizer/yangvisualizer.module','common/layout/layout.module'];
var e = ['oc.lazyLoad', 'ui.router', 'pascalprecht.translate', 'ngSanitize', 'angular.css.injector', 'app','app.testsetup','app.core','app.designboard','app.testautomation','app.common.login','app.common.auth','app.common.nav','app.common.topbar','app.common.general','app.topology','app.yangui','app.common.yangUtils','app.common.sigmatopology','app.yangvisualizer','app.common.layout'];
        // global variables

    </script>

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->

    <!--[if lt IE 9]>
    <script src="assets/js/html5shiv.js"></script>
    <script src="assets/js/respond.min.js"></script>
    <![endif]-->

    <!-- compiled CSS -->
    <link rel="stylesheet" type="text/css" href="vendor/ng-grid/ng-grid.min.css" />
    <link rel="stylesheet" type="text/css" href="vendor/select2-bootstrap-css/select2-bootstrap.css" />
    <link rel="stylesheet" type="text/css" href="vendor/footable/css/footable.core.min.css" />
    <link rel="stylesheet" type="text/css" href="vendor/footable/css/footable.standalone.min.css" />
    <link rel="stylesheet" type="text/css" href="vendor/vis/dist/vis.min.css" />
    <link rel="stylesheet" type="text/css" href="vendor/ng-slider/dist/css/ng-slider.min.css" />
    <link rel="stylesheet" type="text/css" href="assets/opendaylight-dlux-0.2.0.css" />
    <link rel="stylesheet" href="assets/css/sb-admin.css" />

    <script type="text/javascript" data-main="src/main.js" src="vendor/requirejs/require.js"></script>

    <link rel="stylesheet" href="assets/css/font-awesome.min.css" />
    <!-- the font-awesome is different from the 'official' one -->
<link rel="stylesheet" href="src/app/testsetup/testsetup-custom.css" />
<link rel="stylesheet" href="src/app/designboard/designboard-custom.css" />
<link rel="stylesheet" href="src/app/testautomation/testautomation-custom.css" />

    <!-- application CSS -->
  </head>

  <body class="skin-3">
  <div ui-view="mainContent"></div>
  </body>
</html>

3 个答案:

答案 0 :(得分:1)

由于SeleniumgeckodriverFirefox版本之间的不匹配,我发现您所观察到的错误类型。

根据发行说明 Selenium v3.6.0 应与 geckodriver v.0.18.0 (其中 geckodriver v.0.19.0 推荐)。

但是geckodriver v.0.18.0发行说明清楚地提到了以下内容:

  

geckodriver now recommends Firefox 53 and greater geckodriver compatible with Firefox 56 and greater

Firefox 升级到 v53+ 级别肯定会解决您的问题。

更新

根据您的评论,您可以将username字段的定位符更改为以下任意一种:

  1. <强> css_selector

    driver.find_element_by_css_selector("input[name=username]")
    
  2. <强> xpath

    driver.find_element_by_xpath("//input[@name='username']")
    

答案 1 :(得分:0)

有可能你的驱动程序试图在第一次加载后获取用户名字段,失败并出现异常并在重定向之前将其关闭。它需要等待。你可以尝试:

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
...
def test_worked2(self):
    driver = self.driver
    driver.get(base_url)
    WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.NAME, 'username'))).send_keys("xxx")

答案 2 :(得分:0)

我能够通过使用Firefox配置文件来解决这个问题,我不知道它有什么不同,但它确实有效。

创建Firefox个人资料的链接

http://kb.mozillazine.org/Creating_a_new_Firefox_profile_on_Windows

以下是代码

from selenium import webdriver
fp = webdriver.FirefoxProfile('C:/Users/<user name>/AppData/Roaming/Mozilla/Firefox/Profiles/abc3defghij2.ProfileName')
driver = webdriver.Firefox(fp)
driver.get("https://www.example.com/membersarea")