NoSuchElementException, Selenium unable to locate element



  • 问题

    i would like to find my TextField in selenium, but i dont know how (i use sellenium for the first time).

    I tried:

     driver.findElement(By.id(\"originTextField\"))
    
    

    or by xPath and cssSelector String generated by chrome in dev tools.

    Please help me, i would appreciate explanation.

    this is html:

    回答1:

    18

    NoSuchElementException

    org.openqa.selenium.NoSuchElementException popularly known as NoSuchElementException extends org.openqa.selenium.NotFoundException which is a type of WebDriverException.

    NoSuchElementException can be thrown in 2 cases as follows :

    • When using WebDriver.findElement(By by) :

      //example : WebElement my_element = driver.findElement(By.xpath("//my_xpath"));
      
      
    • When using WebElement.findElement(By by) :

      //example : WebElement my_element = element.findElement(By.xpath("//my_xpath"));
      
      

    As per the JavaDocs just like any other WebDriverException, NoSuchElementException should contain the following Constant Fields :

    Constant Field      Type                                        Value
    SESSION_ID          public static final java.lang.String        "Session ID"
    e.g. (Session info: chrome=63.0.3239.108)
    
    DRIVER_INFO         public static final java.lang.String        "Driver info"
    e.g. (Driver info: chromedriver=2.34.522940 (1a76f96f66e3ca7b8e57d503b4dd3bccfba87af1),platform=Windows NT 6.1.7601 SP1 x86)
    
    BASE_SUPPORT_URL    protected static final java.lang.String     "http://seleniumhq.org/exceptions/"
    e.g. (For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html)
    
    

    Reason

    The reason for NoSuchElementException can be either of the following :

    • The Locator Strategy you have adopted doesn't identifies any element in the HTML DOM.
    • The Locator Strategy you have adopted is unable to identify the element as it is not within the browser's Viewport.
    • The Locator Strategy you have adopted identifies the element but is invisible due to presence of the attribute style="display: none;".
    • The Locator Strategy you have adopted doesn't uniquely identifies the desired element in the HTML DOM and currently finds some other hidden / invisible element.
    • The WebElement you are trying to locate is within an <iframe> tag.
    • The WebDriver instance is looking out for the WebElement even before the element is present/visibile within the HTML DOM.

    Solution

    The solution to address NoSuchElementException can be either of the following :

    • Adopt a Locator Strategy which uniquely identifies the desired WebElement. You can take help of the Developer Tools (Ctrl+Shift+I or F12) and use Element Inspector.

      Here you will find a detailed discussion on how to inspect element in selenium3.6 as firebug is not an option any more for FF 56?

    • Use executeScript() method to scroll the element in to view as follows :

      WebElement elem = driver.findElement(By.xpath("element_xpath"));
      ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", elem);
      
      

      Here you will find a detailed discussion on Scrolling to top of the page in Python using Selenium

    • Incase element is having the attribute style="display: none;", remove the attribute through executeScript() method as follows :

      WebElement element = driver.findElement(By.xpath("element_xpath"));
      ((JavascriptExecutor)driver).executeScript("arguments[0].removeAttribute('style')", element)
      element.sendKeys("text_to_send");
      
      
    • To check if the element is within an <iframe> traverse up the HTML to locate the respective <iframe> tag and switchTo() the desired iframe through either of the following methods :

      driver.switchTo().frame("frame_name");
      driver.switchTo().frame("frame_id");
      driver.switchTo().frame(1); // 1 represents frame index
      
      

      Here you can find a detailed discussion on Is it possible to switch to an element in a frame without using driver.switchTo().frame(“frameName”) in Selenium Webdriver Java?.

    • If the element is not present/visible in the HTML DOM immediately, induce WebDriverWait with ExpectedConditions set to proper method as follows :

      • To wait for presenceOfElementLocated :

        new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='buttonStyle']//input[@id='originTextField']")));
        
        
      • To wait for visibilityOfElementLocated :

        new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='buttonStyle']//input[@id='originTextField']")));
        
        
      • To wait for elementToBeClickable :

        new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='buttonStyle']//input[@id='originTextField']")));
        
        

    share|improve this answer

    edited Apr 27 '18 at 7:58

    answered Jan 27 '18 at 5:34

    DebanjanBDebanjanB 63.6k1919 gold badges7070 silver badges126126 bronze badges

    • Thanks for the answer can you please provide the equivalent for python for the executeScript() method ? Thank you ! – Solal Jun 20 at 0:31

    add a comment |

    回答2:

    1

    Your code is correct, I suspect the issue caused the page not complete load when you find the element.

    Try add a long sleep before find element, if adding sleep worked, change sleep to wait.

    Here is the code, It means waiting 10s if the element isn’t present:

    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "originTextField"))
    )
    
    

    share|improve this answer

    edited Jan 27 '18 at 5:47

    blanksky 1344 bronze badges

    answered Jan 27 '18 at 4:12

    yongyong 8,88211 gold badge55 silver badges1515 bronze badges

    add a comment |



最新内容

  • Hello I have created this program to check if a number is a prime number. It works but for some reason says that 999 is a prime number. Where is my mistake. It would be great if someone explained. Thank You!

    Here is my program:

    number = raw_input('Enter a Number: ') nnumber = int(number) prime_range = range(2, nnumber) for x in prime_range: if nnumber % x == 0: print 'Not a Prime Number!' break else: print 'Prime Number!' break

    Trace it. x starts with 2, then tests 999 % 2; it is 1, so else is executed, "Prime number!" is printed, and loop is broken out of. Program ends.

    Instead, you need to print "Prime number!" only when you tested all possibilities for x. The easiest way to do that is to unindent else: (and delete break there):

    for x in prime_range: if nnumber % x == 0: print 'Not a Prime Number!' break else: print 'Prime Number!'

    Python executes else of a for when for completes withoout being broken: exactly what you want.

    If a number is prime, that means no number evenly divides it besides 1 and itself. That mean you need to check every number below it before being able to say the number is prime.

    In your code, you are exiting the loop on the first iteration -- regardless of how large the number is.

    The judgment has a problem, can only be 1 or the prime number is divisible by itself. You judge is only 2 out of the whole is not a prime number, you should use a double loop to do the conditions of judgment

    you are checking for the 1st iteration only. Irrespective of whether it is prime or not it exits from the loop since one of the section i.e either 'if' or 'else' will execute causing the loop to break. The logic would be to check for the entire range of numbers from 2 to (number/2) and if it divides the number at some point it will not be a prime number. If the loop exits after iterating over the entire loop then it is a prime number. Hope you will be able to do it now. Thanks!.

    Your existing code only every tests if the number that you entered is divisible by 2 and then breaks out of the loop, whichever way. You have to check all values lower and only exit if it does find that it's NOT a prime:

    number = raw_input('Enter a Number: ') nnumber = int(number) prime_range = range(2, nnumber) prime = True for x in prime_range: if nnumber % x == 0: prime = False break if prime: print 'Prime Number!' else: print 'Not a Prime Number!'

    来源:https://stackoverflow.com/questions/40210370/program-that-checks-if-a-number-is-prime-number

    read more
  • 容器三大核心概念:镜像,容器,仓库。
    镜像:

    镜像是一个独立的文件系统,里面包含了运行环境和配置类似于一个小小型的linux系统 镜像可由dockerfile来进行构建 镜像是静态的,一经构建就无法更改 镜像是多层存储结构,上一层以下一层为基础

    容器:

    容器是镜像的运行实体,容器基于镜像创建 应用在容器中运行 容器也是多层存储结构,叫容器存储层 也可以根据修改容器构建一个新的镜像

    仓库:

    作用:用于存放镜像文件 要区别于仓库register注册服务器

    来源:https://www.cnblogs.com/jasonboren/p/11370304.html

    read more
  • I\'m trying to send uploaded file and user details to another email ID.Using the below code for Uploading and PHP mailer for sending user details along with uploaded file. But using the code I can upload(fil2) the file but I can\'t send user details or If I will use PHP mailer(mailer7.php),only getting user details but not upload file.

    { throw new RuntimeException(\'Invalid fileToUpload format.\'); } // You should name it uniquely. // DO NOT USE $_FILES[\'file\'][\'name\'] WITHOUT ANY VALIDATION !! if (!move_uploaded_file( $_FILES[\'fileToUpload\'][\'tmp_name\'], sprintf(getcwd().\'/fil2/%s.%s\', sha1_file($_FILES[\'fileToUpload\'][\'tmp_name\']), $ext ) )) { throw new RuntimeException(\'Failed to move uploaded fileToUpload.\'); } echo \'File is uploaded successfully.\'; } catch (RuntimeException $e) { echo $e->getMessage(); }

    I m getting little but confusion using uploadfile and mail.php in one single page

    read more

最新主题

313
Online

339
Users

226.1k
Topics

379.5k
Posts

在线用户

推荐阅读

本站部分内容来自互联网,其发布内容言论不代表本站观点,如果其链接、内容的侵犯您的权益,烦请联系我们,我们将及时予以处理。
Powered by NodeBB | 备案号:宁ICP备15000671号