Selenium (XI): Set elements wait, upload files, download files

1. Set elements waiting

Earlier we contacted several elements wait method, sleep, implicitly_wait method, this chapter we take a look at the whole school.

Now most Web applications are using AJAX technology. When the browser loads the page elements on the page could not be loaded at the same time, which gives the positioning of elements increases the difficulty. If because of delay in loading caused by an element of the case ElementNotVisibleException appear, it will reduce the stability of automation scripts, we can set the elements to wait to improve the instability caused by this problem.

WebDriver provides two types of waiting: waiting for the display and implicit wait.

1.1 shows the wait

Continue to wait for the explicit condition WebDriver waiting for a deal, otherwise abandon timeout exception (TimeoutException) when the maximum duration.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wd = webdriver.Chrome()

wd.get('https://www.baidu.com/')
a = WebDriverWait(wd,10).until(EC.presence_of_element_located((By.ID,"kw")))
a.send_keys('selenium')

WebDriverWait class waiting methods provided by WebDriver. Within the set time, the default time to time be tested once the current page element exists, and if it exceeds the set time does not detect an exception is thrown.

WebDriverWait(driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None)

driver: Driver browser

timeout: maximum timeout, default in seconds

poll_frequency: detecting an interval (step). The default is 0.5S

ignored_exceptions: abnormality information after a timeout, by default, throw an exception NoSuchElementException

WebDriverWait () General and an until () or until_not () method with the use.

until(method, message='')

This method provides the driver is called as a parameter, until the return value is True.

until_not(method, message='')

This method provides the driver is called as a parameter, until the return value is False.

In the example above, as a keyword by the EC expected_conditions rename, and call presence_of_element_located () method for determining whether the element is present.

The method is expected to provide conditions expected_conditions class determination are as follows:

title_is: to determine whether the title of the current page is equal to the expected

title_contains: to determine whether the current page title contains the expected string

presence_of_element_located: to determine whether the element is added to the DOM tree, does not mean necessarily visible elements

visibility_of_element_located: determining whether the element is visible (visible on behalf of a non-hidden elements, and the width and height of the element are not equal to 0)

visibility_of: a method with the same effect, but one method parameter, which parameter is received by the positioning element

presence_of_all_elements_located: determining whether there is at least one element is present in the DOM tree. For example, there are class n elements is "wp" in the page, as long as there is an existing returns True

text_to_be_present_in_element: determining whether an element of the text contains the expected string

text_to_be_present_in_element_value: determine an element value attribute contains the expected string

frame_to_be_available_and_switch_to_it: determining whether the handover into available form, if available, and switch into returns True, False otherwise

invisibility_of_element_located: determining whether an element is not present or is not visible in the DOM tree

element_to_be_clickable: to determine whether the element is visible and clickable

staleness_of: Wait until an element is removed from the DOM tree

element_to_be_selected: determining whether an element is selected, generally used in the drop-down list

element_selection_state_to_be: to determine whether the state of an element of choice in line with expectations

element_located_selection_state_to_be: a method with the same effect, but one element of a method parameter units, the positioning method parameter received

alert_is_present: to determine whether there is a page on alert

In addition to the expected condition judging method rich expected_conditions provided, you may also be used to determine whether the element is visible is_displayed () method. 

from selenium import webdriver
from time import  sleep,ctime

wd = webdriver.Chrome()

wd.get('https://www.baidu.com/')

print(ctime())
for i in range(10):
    try:
        el = wd.find_element_by_id("kw22")
        if el.is_displayed():
            break
    except:pass
    sleep(1)
else:
    print("time out")
wd.close()
print(ctime())

Relatively speaking, this approach is more readily understood through for 10 cycles, each cycle is determined whether or not the element is_displayed () status to True. If True, then break out of the loop; otherwise sleep (1) to continue the cycle after judgment until after 10 cycles, print "time out" information.

Execution results are as follows:

 

1.2 Implicit wait

Implicit wait through a certain length of time to wait for an element on the page has finished loading. If you exceed the duration of an element of the set has not been loaded, an exception is thrown NoSuchElementException. WebDriver mention skill implicitly_wait () method to achieve implicit wait, set to 0 by default. Its usage is relatively much simpler. 

from selenium import webdriver
from selenium.common.exceptions import  NoSuchElementException
from time import ctime

wd = webdriver.Chrome()

#设置隐式等待为10秒
wd.implicitly_wait(10)
wd.get('https://www.baidu.com/')

try:
    print(ctime())
    wd.find_element_by_id("kw22").send_keys('selenium')
except NoSuchElementException as e:
    print(e)
finally:
    print(ctime())

Implicitly_wait () for the second unit of default parameters, the present embodiment is set to wait 10 seconds long. First, this is not a fixed 10 seconds of waiting time. It does not affect the speed of execution of the script. Secondly, it does not wait for a certain element on the page. When the script execution to locate an element, if the element can be positioned, continue; if not positioning element, it will continue in a cyclic manner queries determine whether the element is positioned. Assuming the first three seconds of the targeting element, proceed, if they know the long (10 seconds) has not exceed the target element is provided, an exception is thrown.

In the above example, it is clear Baidu positioning input box id = kw22 be erroneous, can be seen two time printed, when the operation of the input box Baidu, waiting for more than 10 seconds.

1.3 sleep sleep method

In the front we used the method of sleep, but there is no detail, now put this fall into this broad heading to introduce.

Sometimes we do want the script to sleep at a fixed time of execution to a certain position, especially in script debugging. Then you can use the sleep () method, should be noted that, sleep () method provided by the python time module. 

from selenium import webdriver
from time import sleep

wd = webdriver.Chrome()

wd.get('https://www.baidu.com/')

sleep(2)
wd.find_element_by_id("kw").send_keys("selenium")
wd.find_element_by_id("su").click()
sleep(5)

wd.quit()

When performing the sleep () method will be a certain fixed length of the sleep, and then proceed. sleep () method default parameters in seconds, if the set length is less than 1 second, can be expressed as a decimal, if sleep (0.5) represents the sleep 0.5 seconds.

2. Upload file

Upload files is one of the more common Web functions, but does not provide a method WebDriver specifically for uploading, upload the key is how the idea to upload files.

After the operation uploading Web pages generally need to click the "Upload" button to open a local Window window, select a local file to upload from the window. The WebDriver Windows controls is inoperable, therefore, for starters, the general idea will be stuck on how to identify Window control this problem.

For uploading Web pages are generally achieved at in two ways.

Ordinary Upload: Upload a common accessory is the path to a local file as a value on the input tab, this value will be submitted to the server via form form.

Upload plugin: generally refers to uploading and other features based on Flash, JavaScript or Ajax technologies implemented.

Upload automation plug-ins that do not fit inside the explanation may be placed in high-level programming python inside explain. By uploading input tag for implementation, it may be considered an input box, the way to achieve local file path specified by the file upload send_keys ().

html code:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/liuhui0308/p/11960883.html