Several ways to resolve page elements that cannot be located (nosuchelementexception:unable to locate Element)

Source: Internet
Author: User
Tags xpath

只解决一个问题--NoSuchElementException: Message: Unable to locate element
Cause of error 1. Possible element loading not completed

Element loading is not completed, the same path location, each test results are not the same, sometimes throw errors, sometimes normal! This is compared to the egg pain, that is, and your location method of the half-dime relationship is not, and much depends on your computer and network speed!

1. Solution A: Add two lines of code
wait = ui.WebDriverWait(driver,10)wait.until(lambda driver: driver.find_element_by_方法("定位路径自己来"))
    • 1
    • 2

Webdriverwait (driver,10) means that 1 page changes are scanned every 500 milliseconds in 10 seconds, ending when the specified element appears. Driver is the handle to the front operation Webdriver.firefox ()
The complete small segment code is:

from Selenium import Webdriverimport selenium< Span class= "Hljs-preprocessor" >.webdriver.support .ui as Uidriver_item=webdriver "https://movie.douban.com/" wait = Ui10) driver_item.get (URL) Wait.until (lambda driver:driver.find_element_by _xpath ( "//div[@class = ' fliter-wp ']/div/form/div/div/label[5]")) Driver_item.find_element_by_xpath ( "//div[@class = ' fliter-wp ']/div/form/div/ DIV/LABEL[5] ".click ()         
1. Solution B: Use while+try...except to combine

Here's an example of the complete operational code as follows:

from selenium  Import Webdriverimport timeimport osdriver_item=webdriver. Firefox () Url= "https://movie.douban.com/" Driver_item.get (URL) while 1:start = Time.clock () try: Driver_item.find_element_by_xpath ( "//div[@class = ' fliter-wp ']/div/form/div/div/label[ 5] "). Click () print  ' positioned to element ' End=time.clock () break except: print  "not yet anchored to the element!" print  ' positioning time: ' +str (end-start)      
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

The results of the operation are as follows:

还未定位到元素!已定位到元素定位耗费时间:0.262649990301
    • 1
    • 2
    • 3
Analysis

After the page is opened, not all elements are loaded at once, depending on the speed and computer, from the B method can be seen, the time spent, there is a static method is I used to sleep, generally sleeping a second is enough, but for different computers different speed situation, it is recommended to use dynamic method, that is, a method To change the strain!

From the code readability and efficiency are a method better, more in line with the characteristics of Python, concise and beautiful, and B method should be I so beginners themselves can think of a method, first have to think about the solution, and then refer to the existing methods, I feel that it makes sense.

2. Error in positioning method itself

This is the most common, but also the most easy to make mistakes, their position on the element is not skilled enough, it is easy to mistake, so much to think about how to locate the most easily, I now most like to use the XPath method of positioning, the structure of the DOM tree is very clear, maybe I still novice reason it!

2. Solution

Multi-Query element location method, multi-use more skilled, spit groove a bit ... Compared to the regular, I prefer beautifulsoup or XPath to use, the amount ...

Let's say I'm going to look at how the BeautifulSoup works, and I'll write a test module alone.

#-*-Coding:utf-8-*-from bs4 import Beautifulsoupimport re#find_all () and find () only search all child nodes of the current node, grandson nodes, etc. # find_parents () and F Ind_parent () is used to search the parent node of the current node, # Search method is the same as normal tag search method, search document Search document contains content HTML = "" "<Html><Head><Title>the Dormouse ' s story</Title></Head><Body><Pclass="Title"Name="Dromouse" ><B>the Dormouse ' s story</B></P><Pclass="Story" >once upon a time there were three Little sisters; and their names were<Ahref="Http://example.com/elsie"class="Sister"Id="Link1" ><!--Elsie--</A>,<Ahref="Http://example.com/lacie"class="Sister"Id="Link2" >lacie</a> and<a href= "Http://example.com/tillie" class= "sister" id= "Link3" >tillie</a>;and they lived at the Bottom of a well. </p>< P class= "story" ..... </p> "" "Soup=beautifulsoup (HTML," lxml ") #soup = BeautifulSoup (Open (' index.html '), "lxml") #若本身有html文件, open #print soup.prettify () print Soup.titleprint Soup.a.stringprint soup.a[' href ']print soup.a[' class ']         
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 20
    • 21
    • 22
    • Li style= "color: #999999" >23
    • 24
    • 25
    • 26
    • 27

I would like to make an analogy, when I want to use the BS4 I will test their own rules alone, after all, not the old driver.

Tips

1. The test phase calls Firefox to do, so more intuitive and specific, to the end can call Phantomjs.exe.

2. Sub-module test your idea, light think far enough.

3. Preferably a split-screen computer, one screen display code, one screen display implementation process

Summarize

Encounter problems seem to need step by step, analysis of the cohesion between the modules and module integrity, separate modules out to test, or a larger point of the program error in which are very laborious, and, if it is written by the program, then recommended step by step implementation, which step should be the function of which step, so the logic is clear enough , it is written to my own words, if it is helpful to you, I also feel very honored!

 

Several ways to resolve page elements that cannot be located (nosuchelementexception:unable to locate Element)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.