The presence of selenium causes of abnormal automatic page elements are the following:
① page load time is too slow, need to find the elements of the program have been completed, but the page has not loaded successfully. At this point you can load the page waiting time.
Element ② looking for is not in the current frame or iframe in. At this time you will be switched in the corresponding frame or iframe job.
③ Element errors.
Page load time solving elements caused can not find, you can set the time for the page to load. Time settings are divided into the following three:
1, shows the wait WebDriverWait ()
2, implicit wait implicitly_wait ()
3, forced to wait for sleep ()
WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None)
Description: The driver of the driver ----- WebDriver
timeout ------ maximum timeout, in seconds
poll_frequency ------- interval (step) of the sleep time period, the default is 0.5 seconds
Ignored_exceptions ------- exception information after the timeout, default NoSuchElementException throw an exception
E.g:
WebDriverWait(driver, 10).until(lambda driver:driver.findElement(By.Id("someId")));
Every 0.5 seconds to scan a check for an id somdld, did not find not find 10 seconds, throw an exception.
Simple code to achieve:
import time
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriver
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
element = WebDriverWait(driver, 10).until(lambda driver:driver.find_element_by_id("kw"))
element.send_keys("selenium")
# Add smart wait
driver.implicitly_wait(30)
driver.find_element_by_id('su').click()
time.sleep()
driver.quit()