Python + selenium FAQ, flash back, element not found, page nesting, forced waiting time too long
1、 Flashback problem : Due to the lack of browser corresponding driver . Google :chromedriver drive ; firefox :geckodriver drive
When downloading Firefox driver, you should pay attention to : First check your installed browser version , Download the corresponding version from the official driver
After downloading the driver , Need to be placed in python Install under directory Scripts Under the document , Then restart the project , Some computers need to be restarted .
2、 The element not found is divided into several conditions :(1) Missing driver ;(2) Page nesting ;(3) Page element not loaded ;(4) There are several situations such as dynamic loading of page elements
(1) Missing driver : Based on the above 1、 Download driver , that will do .
(2) Page nesting : Check whether the element exists above the label iframe label , Or new <html>、<body> Such as tag , If it exists , You need to enter the new page first and then find the elements .
(3) Page element not loaded : This problem occurs because the page is loaded asynchronously , On the web , The page has been displayed , But the actual elements , Not loaded yet , Just look for the element and operate , It will cause the element not to be found , And keep it wrong , So how to avoid this situation , That’s waiting , Forced waiting or implicit waiting , Wait for element loading to complete
Mandatory waiting :time.sleep( Waiting time )
An implicit wait : If the forced waiting time is too long , You can choose to wait implicitly , Implicit waiting is an approximate time set by yourself , If the element is loaded within that time , Then keep going , If not loaded , An error is reported or an exception message set by yourself is thrown , The following example , Set the time to 10 second .
# Implicitly wait for the required import
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
curpath = os.path.dirname(os.path.realpath(__file__))
cfgpth = os.path.join(curpath, "C:/Users/Admnistrater/PycharmProjects/pythonProject/pz.ini")
conf = configparser.ConfigParser()
conf.read(cfgpth, encoding="utf-8")
divs = int(conf.get("PZ", "divs"))
driver = webdriver.Firefox()
# An implicit wait
local = (By.ID, "username")
WebDriverWait(driver, 10).until(EC.presence_of_element_located(local))
driver.find_element_by_id("username").send_keys(conf.get("PZ", "username"))
Read more here: Source link