简体   繁体   中英

Selenium/Python can't find input

I'm using Selenium and Python to test my website and i found a problem. After clicking an anchor tag, i'm not able to find an input on the page.

I've found two "solutions" for this problem here in StackOverflow but they don't work for me.

This is my Python code:

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

The problems appears at the "vista_registro" function. I'm clicking over the anchor tag > changing the actual window (not opening a new one) > trying to get my input by its ID: "firstname".

This is the register.blade.php file (Register view)

@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

Console LOG:

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 for the homepage:

<!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>

The problem isn't with the registration form. The problem is with the outer loop you use to find and click the link to the registration page.

The CSS selector div a matches 7 elements—the 4th of which is the link to the registration page. After you click the 4th link, the browser navigates to the registration page and your vista_registro() function is excecuted—successfully.

After the function completes, it returns to the loop, where you attempt to click the 5th link. Because the browser is no longer on the home page, the elements you're looping over are "stale"—that is, they no longer exist on the page (they belonged to the previous page). Hence, a StaleElementReferenceException is raised.

A naive solution

You likely want to stop looping over the links after you click the link to the registration page. The quickest way to do that is to add a break after your call to vista_registro() .

A far better solution

But there's a much simpler way to find a link with some particular text in Selenium: find_element_by_link_text .

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

With this, you don't need a loop or a break .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM