Python+Selenium Failure to Locate Elements Common Causes and Solutions of Report: NoSuchElementException

  • 2021-10-13 08:14:45
  • OfStack

In the automated test of web application, it is essential to locate elements. This process often encounters the situation that elements cannot be located (reported to selenium. common. exceptions. NoSuchElementException), which can be solved from the following aspects:

1. Frame/Iframe cause element not located:

This is the most common reason. First of all, we should understand the essence of frame. In fact, another page is embedded in frame, while webdriver can only be identified on one page at a time. Therefore, we need to locate the corresponding frame first and locate the elements in that page.

Solution:

If iframe has name or id, use switch_to_frame ("name value") or switch_to_frame ("id value") directly. As follows:


driver=webdriver.Firefox()
driver.get(r'http://www.126.com/')
driver.switch_to_frame('x-URS-iframe') # You need to jump to iframe Framework 
username=driver.find_element_by_name('email')
username.clear()

If iframe does not have name or id, it can be located in the following way:


# Navigate to first iframe
elementi= driver.find_element_by_class_name('APP-editor-iframe')
# Then the positioning object is passed to switch_to_frame() Method 
driver.switch_to_frame(elementi) 

If the operation is complete, you can jump out of the current iframe through the switch_to.parent_content () method, or you can jump back to the outermost page through the switch_to.default_content () method.

2. Xpath describes the cause of the error:

Because Xpath hierarchy is too complex, it is easy to make mistakes. However, this positioning method can effectively locate most elements, so it is recommended to master it.

Solution:

2.1 You can copy the xpath path using firePath of Firefox. This method is easy to rewrite the xpath path because of the hierarchy change, so it is not recommended. Beginners can copy the path first and then try to modify it.

2.2 Improve the level of writing xpath.

You can see the summary of another blog post of the author in detail: the element positioning summary and example explanation of Selenuim+Python
This blog post summarizes the use of Xpath in detail, and multi-combination positioning 1 can achieve positioning problems.

How to verify that Xpath is written correctly? Write Xpath path, you can directly copy to Sohu browser firebug to view html source code, through Xpath search: the following red box, if there is no error, it means that the written Xpath path is correct.


find_element_by_xpath("//input[@id='kw']")

3. The action on the elements on the page before the page is loaded:

In this case, 1 generally speaking, you can set waiting and wait for the page to be displayed before operating, which is similar to the principle of manual operation:
3.1 Set the waiting time; The disadvantage is that it needs to set a long waiting time, and the test is very slow when there are many cases;
3.2 Set to wait for an element of the page to appear, such as 1 text and 1 input box, and you can do the operation once the specified element appears.
3.3 In the process of debugging, you can print out the html code of the page for analysis.

Solution:
Import the time module.


import time
time.sleep(3)

4. Dynamic id does not locate elements:

Solution:
If dynamic id is found, locate directly with xpath or other methods.

5.2 positioning times, such as pop-up login

If Baidu login pop-up box logs in to Baidu account, you need to navigate to Baidu pop-up box first, and then navigate to user name and password login.


# coding=utf-8
'''
Created on 2016-7-20
@author: Jennifer
Project: Log in to Baidu account 
'''
from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.get("http://www.baidu.com/")

time.sleep(3)

# Click to log in: Some name For tj_login The element of is invisible, so click the visible login button. 
# Otherwise, it will report: ElementNotVisibleException
element0=driver.find_elements_by_name("tj_login")
for ele0 in element0:
  if ele0.is_displayed():
    ele0.click()

# In the login pop-up box, you need to navigate to the login pop-up box first 
# Otherwise, it will report: NoSuchElementException
element1=driver.find_element_by_class_name("tang-content")
element11=element1.find_element_by_id("TANGRAM__PSP_8__userName")
element11.clear()
element11.send_keys(" Login name ")

element2=element1.find_element_by_id("TANGRAM__PSP_8__password")
element2.clear()
element2.send_keys(" Password ")

element3=element1.find_element_by_id("TANGRAM__PSP_8__submit")
element3.click()
element3.submit()

try:
  assert " Login name " in driver.page_source
except AssertionError:
  print " Login failed "
else:
  print " Login Successful "
  time.sleep(3)
finally:
  print " Test record: tested "
driver.close()

Supplement: Newspaper: selenium. common. exceptions. ElementNotVisibleException

Code:


from selenium import webdriver
from PIL import Image
import time
import pandas as pd
import datetime
 
driver = webdriver.Ie(r"C:\Program Files\internet explorer\IEDriverServer2.exe")
driver.get("https://www.cib.com.cn/cn/minipage/page/login-firmalert.html")
print(" Please enter the user name and account password to log in ")
input("==== Press any key to continue ====")
 
# print(driver.current_url) # https://corporatebank.cib.com.cn/firm/main/mainx.do
 
frame = driver.find_element_by_id("workframe") #  Switch to  iframe  Find in the tag 
driver.switch_to_frame(frame) #  Cut in  iframe  Label 
 
# driver.switch_to_default_content()  #  Cut out  iframe  Label   You can also   Direct   Default 
 
driver.find_element_by_xpath('//div[@id="fast-way"]/ul/li[2]/a').click() #  Click   Details query button of the day 
time.sleep(2)
try:
  driver.find_element_by_xpath('//div[@id="fast-way"]/ul/li[2]/a').click() #  Click   Details query button of the day 
except Exception as e:
  print("======= Double-click this button ========", e)
time.sleep(3)


Related articles: