简体   繁体   English

Selenium / Python找不到输入

[英]Selenium/Python can't find input

I'm using Selenium and Python to test my website and i found a problem. 我正在使用Selenium和Python测试我的网站,但发现了问题。 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. 我在StackOverflow上找到了两个针对此问题的“解决方案”,但它们对我不起作用。

This is my Python code: 这是我的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()

The problems appears at the "vista_registro" function. 问题出现在“ vista_registro”函数中。 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". 我单击锚标记>更改实际窗口(不打开新窗口)>尝试通过其ID:“名字”获取输入。

This is the register.blade.php file (Register view) 这是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

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: 主页的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>

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. CSS选择器div a匹配7个元素,其中第4个是指向注册页面的链接。 After you click the 4th link, the browser navigates to the registration page and your vista_registro() function is excecuted—successfully. 单击第四个链接后,浏览器导航到注册页面,并且成功执行了vista_registro()函数。

After the function completes, it returns to the loop, where you attempt to click the 5th link. 函数完成后,它将返回到循环,您尝试单击第5个链接。 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. 因此,引发了StaleElementReferenceException

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() . 最快的方法是在调用vista_registro()之后添加一个break

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 . 但是,有一种简单得多的方法来查找带有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 . 这样,您就不需要循环或break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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