Selenium / Python无法找到输入

时间:2018-03-14 00:05:38

标签: python selenium

我使用Selenium和Python测试我的网站,我发现了一个问题。点击锚标记后,我无法在页面上找到输入。

我找到了两个"解决方案"对于StackOverflow中的这个问题,但它们不适合我。

这是我的Python代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Inicia chrome > ingresa al host local > verifica que el título del sitio coincide con el de mi proyecto
driver = webdriver.Chrome('./chromedriver')
driver.get("http://localhost:8000")
assert "ArtStick" in driver.title

def main():

    # Ubica todos los HTML anchor <a> que estén dentro de un div
    anchors = driver.find_elements_by_css_selector('div a')
    # Recorre la lista creada
    for anc in anchors:

        # Obtiene el texto del anchor
        a_tag = anc.get_attribute("text")

        # Evalúa el texto de un anchor
        if 'Registrarse' in a_tag:

            # Envía el elemento (<a>) si su texto es igual a "Registrarse"
            vista_registro(anc)

def vista_registro(anc):

    # Hace click en el anchor para ir a la vista de registro
    anc.click()

    element = WebDriverWait(driver, 120).until(
        EC.presence_of_element_located((By.ID, "firstname"))
    )

    print(element)


main()

问题出现在&#34; vista_registro&#34;功能。我点击锚标记&gt;改变实际窗口(不打开新窗口)&gt;试图通过其ID输入我的输入:&#34; firstname&#34;。

这是register.blade.php文件(注册视图)

@extends('layouts.app')

@section('content')
<div id="register">
  <div class="ui middle center aligned grid">
    <div class="five wide column">
      <form class="ui large form" method="POST" action="{{ route('register') }}">
        {{ csrf_field() }}

        <div class="ui stacked segment">
          <h2 class="ui header left aligned blue">
            <img src="{{ asset('/images/logo.png')}}" class="ui image">
            <div class="content">
              Registrarse
              <div class="sub header">ArtStick — Comunidad Artística</div>
            </div>
          </h2>
          <div class="ui divider"></div>

          <div class="two fields">
            <div class="field">
              <div class="ui left icon input">
                <i class="user circle icon"></i>
                <input type="text" name="firstname" id="firstname" placeholder="Nombre" value="{{ old('firstname') }}" required>
              </div>
            </div>
            <div class="field">
              <div class="ui left icon input">
                <i class="user circle outline icon"></i>
                <input type="text" name="lastname" id="lastname" placeholder="Apellido" value="{{ old('lastname') }}" required>
              </div>
            </div>
          </div>

          <div class="field">
            <div class="ui left icon input">
              <i class="user icon"></i>
              <input type="text" name="username" id="username" placeholder="Usuario" value="{{ old('username') }}" required>
            </div>
          </div>

          <div class="field">
            <div class="ui left icon input">
              <i class="mail icon"></i>
              <input type="email" name="email" id="email" placeholder="Correo elctrónico" value="{{ old('email') }}" required>
            </div>
          </div>

          <div class="field">
            <div class="ui left icon input">
              <i class="unlock alternate icon"></i>
              <input type="password" name="password" id="password" placeholder="Contraseña" required>
            </div>
          </div>

          <div class="field">
            <div class="ui left icon input">
              <i class="lock icon"></i>
              <input type="password" name="password_confirmation" id="password-confirmation" placeholder="Confirmar Contraseña" required>
            </div>
          </div>

          <div class="field">
            <div class="ui checkbox" id="terms">
              <input type="checkbox" tabindex="0" class="hidden" id="terms-input">
              <label for="terms-input">Acepto los <a href="#">Términos y Condiciones</a></label>
            </div>
          </div>

          <button class="daltong ui fluid large green submit button" type="submit">Enviar</button>
          <div class="ui divider"></div>
          <div class="ui icon message">
            <i class="icon sign in"></i>
            <div class="content">
              <div class="header">
                ¿Posees una cuenta? <a href="{{ route('login') }}">Inicia sesión</a>
              </div>
              <p>¡No pierda ni un segundo más!</p>
            </div>
          </div>
        </div>
      </form>
    </div>
    <div class="five wide column left aligned">

      <div class="ui icon message">
        <i class="calendar outline icon"></i>
        <div class="content">
          <div class="header">
            Desafíos
          </div>
          <p>Participa en eventos mensuales de la comunidad.</p>
        </div>
      </div>

      <div class="ui icon message">
        <i class="archive icon"></i>
        <div class="content">
          <div class="header">
            Álbumes
          </div>
          <p>Organiza todos tus diseños.</p>
        </div>
      </div>

      <div class="ui icon message">
        <i class="star half empty icon"></i>
        <div class="content">
          <div class="header">
            Críticas
          </div>
          <p>Recibe o proporciona ánalisis.</p>
        </div>
      </div>

      <div class="ui icon message">
        <i class="heart icon"></i>
        <div class="content">
          <div class="header">
            Favoritos
          </div>
          <p>Agrega diseños a tu lista de recuerdos.</p>
        </div>
      </div>

    </div>
  </div>
</div>

@endsection

控制台日志:

DevTools listening on ws://127.0.0.1:12629/devtools/browser/d2d7dc4e-b125-451f-88ee-bce85811d701
[372:5204:0313/203153.450:ERROR:gpu_process_transport_factory.cc(1009)] Lost UI shared context.
Traceback (most recent call last):
  File "selecode.py", line 39, in <module>
    main()
  File "selecode.py", line 21, in main
    a_tag = anc.get_attribute("text")
  File "C:\Users\Félix Bejarano\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 143, in get_attribute
    resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name})
  File "C:\Users\Félix Bejarano\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webelement.py", line 628, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\Félix Bejarano\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Félix Bejarano\AppData\Local\Programs\Python\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=64.0.3282.186)
  (Driver info: chromedriver=2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91),platform=Windows NT 10.0.16299 x86_64)

主页的driver.page_source CONSOLE LOG:

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

          <meta name="authUsername" content="guest" />
      <meta name="authUserID" content="0" />
      <meta name="authUserAvatar" content="public/defaults/avatars/default.jpg" />

    <!-- CSRF Token -->
    <meta name="csrf-token" content="Wn5vzZtSr8wadeJTRyZ9A0VsSkDDYFrfTmZ92FOD" />

    <title>ArtStick</title>

    <!-- Styles -->
    <link href="http://localhost:8000/css/app.css" rel="stylesheet" />


    <!-- jQuery -->
    <script src="http://localhost:8000/js/jquery.min.js"></script>

    <!-- Semantic UI -->
    <link rel="stylesheet" type="text/css" href="http://localhost:8000/css/semantic.min.css" />
    <script src="http://localhost:8000/js/semantic.min.js"></script>

    <!-- Semantic JQuery Specs -->
    <script src="http://localhost:8000/js/semantic-esp.js"></script>

    <!-- Favicon -->
    <link rel="icon" href="http://localhost:8000/images/logo.png" />

<style type="text/css">
.grid {
  position: relative;
  margin: 5% auto;
}
.white-outline {
  outline: 2px solid #FFF;
  outline-offset: -2px;
}
</style></head>
<body class="dimmable">
    <div id="app"><div id="main-navbar" class="ui inverted menu"><div class="ui container"><a href="/" class="header item"><img src="http://localhost:8000/images/logo.png" class="logo" /></a> <a href="/" class="item">
      Indice
    </a> <div class="item"><div class="ui icon input"><input type="text" name="busqueda" placeholder="Búsqueda..." /> <i class="circular search link icon"></i></div></div> <div class="right menu"><a href="http://localhost:8000/login" class="item">
          Ingresar
        </a> <a href="http://localhost:8000/register" id="registerbutton" class="item">
          Registrarse
        </a> <div class="ui simple dropdown item" tabindex="0">
        Opciones
        <i class="dropdown icon"></i> <div class="menu" tabindex="-1"><a href="#" class="item">
            Términos &amp; Condiciones
          </a> <a href="#" class="item launchelp">
            Ayuda
          </a> <div class="divider"></div> <div class="header">ArtStick 0.1.0</div> <a href="#" class="item">
            Ver notas de la versión
          </a></div></div></div></div></div>  <div id="uploads-grid"><div class="grid" style="position: relative; width: 300px; height: 0px;"></div></div></div>

    <!-- Scripts -->
    <script src="http://localhost:8000/js/app.js"></script>


<div class="ui dimmer modals page"><div class="ui modal helpmodal"><div class="header">¿Necesitas ayuda?</div> <div class="scrolling content"><p></p><h3 class="ui header">Registro</h3> <p class="justified">Cupcake ipsum dolor sit amet donut sugar plum. Sesame snaps pie bear claw biscuit. Toffee dessert macaroon I love. Chocolate caramels lollipop. Lollipop sweet cotton candy chocolate cake lemon drops gummi bears. Gummi bears dragée donut. Cookie cheesecake lemon drops. Cookie brownie fruitcake sesame snaps powder.</p> <h3 class="ui header">Ingreso</h3> <p class="justified">Tootsie roll sesame snaps caramels. Lemon drops brownie cheesecake sweet gummies. Pudding lollipop candy I love. Tiramisu cotton candy bonbon bonbon cupcake I love sugar plum. Ice cream icing halvah gummi bears tootsie roll jelly-o. Tootsie roll gingerbread jelly-o bonbon sweet fruitcake I love chocolate bar jujubes. Marzipan fruitcake carrot cake oat cake chocolate bar chocolate.</p> <h3 class="ui header">Perfil &amp; Edición</h3> <p class="justified">Chocolate icing bear claw bear claw dragée fruitcake. I love croissant cookie caramels fruitcake danish gummies. Cake halvah cookie icing. Chocolate pie topping cupcake candy bonbon bear claw. Carrot cake jelly beans caramels liquorice soufflé cotton candy. Lemon drops cake biscuit apple pie chocolate cake jelly-o marzipan biscuit carrot cake. Chocolate cake marshmallow bear claw I love.</p> <h3 class="ui header">Administrar álbumes</h3> <p class="justified">Candy canes cookie cake cake. Icing jelly-o candy sweet roll jelly beans lollipop muffin cake marzipan. Apple pie ice cream brownie lollipop topping I love candy chocolate bar. Jelly-o topping gummi bears I love muffin marshmallow sweet cheesecake. Soufflé jujubes candy croissant cotton candy I love gummi bears macaroon.</p> <h3 class="ui header">Seguidos &amp; Seguidores</h3> <p class="justified">Candy canes cookie cake cake. Icing jelly-o candy sweet roll jelly beans lollipop muffin cake marzipan. Apple pie ice cream brownie lollipop topping I love candy chocolate bar. Jelly-o topping gummi bears I love muffin marshmallow sweet cheesecake. Soufflé jujubes candy croissant cotton candy I love gummi bears macaroon.</p> <p></p></div></div></div></body></html>

1 个答案:

答案 0 :(得分:0)

问题不在于注册表格。问题在于您使用外部循环查找并单击链接注册页面。

CSS选择器div a匹配7个元素 - 其中第4个是注册页面的链接。单击第4个链接后,浏览器将导航到注册页面,并且vista_registro()功能已成功完成。

函数完成后,它将返回循环,您尝试单击第5个链接。由于浏览器不再位于主页上,因此您循环播放的元素是“过时的” - 也就是说,它们不再存在于页面上(它们属于上一页)。因此,StaleElementReferenceException被提升。

天真的解决方案

单击指向注册页面的链接后,您可能希望停止循环链接。最快捷的方法是在致电break后添加vista_registro()

更好的解决方案

但是,在Selenium中查找包含某些特定文字的链接的方法要简单得多:find_element_by_link_text

link = driver.find_element_by_link_text("Registrarse")
link.click()

有了这个,你就不需要循环或break