01,frame/iframe Form nesting

WebDriver Elements can only be identified and located on one page , about frame/iframe Page elements embedded in the form cannot be directly located .

resolvent :


switch_to.frame() By default, the form can be accessed directly id or name attribute . If no is available id and name attribute , You can navigate to frame/iframe, Then transfer the positioning object to switch_to.frame( object ) method .
xf = driver.find_element_by_xpath('//*[@class="if"]')
driver.switch_to.frame(xf) ...
driver.switch_to.parent_frame()  Cut to parent frame. Affect performance , Can be presented to the developer , Let it improve .
driver.switch_to.default_content()  Jump back to the outermost page
02, Page Jump to new tab , Or pop up warning box, etc

Sometimes during page operation, clicking a link will pop up a new window , At this time, you need to switch the focus to the new window for operation .

resolvent 1:

driver.switch_to.window(window_handle) Switch to new window .

First, get the handle of the current window driver.current_window_handle, Then open a new pop-up window , Get the handle of all currently open windows
. adopt for Loop traversal handle, If not equal to the handle of the first open window , Then it must be the handle of the new window , Because only two windows are opened during execution ; change a condition , If equal to the handle of the first open window , Then you can switch back to the first open window .

resolvent 2:

about JavaScript Generated alert,confirm as well as prompt, Unable to use front-end tools to locate pop-up windows , use
driver.switch_to.alert Method positioning Popup .

alert The methods are :

.accept()    ' Equivalent to clicking “ confirm ” or “OK”'

.dismiss()    ' Equivalent to clicking “ cancel ” or “Cancel”'

.text        ' obtain alert Text content , For those with information alert frame '

.send_keys(text)    ' Send text , For those who need to submit prompt frame '

.authenticate(username,password)    ' verification , For those requiring authentication alert'

03, Page elements lose focus, leading to unstable script operation

resolvent :

  Encountered script instability , Sometimes, the test fails due to the loss of focus , You can switch to the focus element before operation . be careful .active_element No parentheses after ().

The following is a reference case :

' initial “ Right click the mouse → New folder → Enter folder name ” Code of '
l = driver.find_element_by_id('pm_treeRoom_1_span')
driver.find_element_by_class_name('fnew').click() time.sleep(2)
As a result, this operation will always cause the input box to lose focus , Disappear directly , Not to mention send_keys Go in , Direct error reporting .

' The modified code is as follows '
driver.find_element_by_class_name('fnew').click() time.sleep(2)
driver.switch_to.active_element.send_keys('filename') time.sleep(2)
04, use Xpath or CSS location

find_element_by_xpath("// label [ attribute =' value ']")

use Xpath/CSS method , It is very suitable for dynamic generation of location attribute values , Elements that are not easy to locate . If you do not want to specify a label , You can use “*” replace , use xpath Not limited to id,name and class These three attributes , Any attribute value of the element can be used , As long as it can uniquely identify an element .

resolvent 1:

If an element has no unique attribute , Then we can look up level by level , Until we find the attribute that can uniquely locate the element , Then look down for its child elements .

find_element_by_xpath("//form[@id='form']/span[2]/input")  First, uniquely identify the attribute id=form Locate outermost element , Then find the second element under the outermost element 2 individual span The element of the label is the parent element , Finally, look down and locate the label under the parent element as input Child element of .

resolvent 2:

If an attribute cannot uniquely distinguish an element , Then use multiple attributes to uniquely locate an element .
  First find the label as input,id=kw And class=su Element of , Then find the label below it as span Child element of , Continue to look down and find the label is input Child element of .

resolvent 3: inspect Xpath Whether the description is incorrect , Cause unable to navigate to element .

05, Operate the elements on the page before the page is loaded

Script failure due to delay in loading elements , We can improve the stability of automated scripts by setting the waiting time .

resolvent 1:

WebDriverWait() Show waiting . Wait for a single element to load , Usually cooperate until(),until_not() Method use .

Namely ,WebDriverWait(driver, Timeout duration , Call frequency , Ignore exceptions ).until( Executable method , Information returned when timeout occurs )

The maximum waiting time is 5s, every other 1 Check every second id='kw' Whether the element of is loaded in DOM In the tree ( It does not mean that the element must be visible ). Most commonly used method
yes expected_conditions Expected condition judgment provided by class .
is_disappeared= WebDriverWait(driver, 30, 1,
(ElementNotVisibleException)).until_not(lambda x:
The maximum waiting time is 30s, every other 1 Check every second id='someId' Whether the element of is from DOM Disappear in the tree , Ignore default exception information NoSuchElementException
  And specified exception information ElementNotVisibleException. Anonymous function here lambda Specific reference for usage of Python grammar .

resolvent 2:

driver.implicitly_wait( second )
  Implicit waiting . Global wait , Set timeout for all elements , Wait for the page to load , Therefore, you only need to set it once . The time here is the longest waiting time ( Non fixed waiting time ).

resolvent 3:

sleep( second ) Thread waiting . Sleep fixed time , You need to import it first when using it time Modular sleep method from time import sleep.

06, Element is blocked , Not available , invisible

resolvent 1:

driver.maximize_window() Page element layout changes due to window size changes , The tested element is blocked , You can maximize the window first , Then locate the element .

resolvent 2:

.is_enabled() Elements are not available in some cases due to business reasons ( Element attribute disabled, Grayed out ), First, check whether the test steps conform to the business logic , Secondly, confirm whether it is in the business process Bug.

resolvent 3:

.is_displayed() For elements whose attributes are not necessarily visible , Before positioning, first judge whether its attribute is visible , Whether it is hidden .

resolvent 4:

Elements covered due to unreasonable layout , Or the problem of unable to locate caused by the absence of the element itself belongs to Bug, It can be proposed to the development department for improvement .

07, use WebDriver call JavaScript Code replaces functions that cannot be realized

For some WebDriver There are no methods provided or functions that cannot be realized ,WebDriver Provided driver.execute_script()
Method to execute JavaScript code .

resolvent :

If the page content is too long , Window maximization can not see all elements , Can be executed by JavaScript The script realizes the dragging of the scroll bar and other actions .
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
The above statement realizes the function of pulling the page to the bottom , among window.scrollTo( left , top margin )
yes JavaScript Code used to set the horizontal and vertical position of the browser window scroll bar in .
text = "input text" driver.execute_script("var
obj=document.getElementById('text'); obj.value=' " + text + " ';")
Suppose an input box can be accessed through id='text' Position it , But I can't pass send_keys() Enter text content , With the help of JavaScript Code to implement .
video = driver.find_element_by_xpath("body/Section[1]/div/video") url =
driver.execute_script("return arguments[0].currentSrc;", video) print(url)    
      ' Return to the file playback address ' print("start")      ' Play video ' driver.execute_script("return
arguments[0].play()", video) sleep(15)           ' play 15 second ' print(stop)        
' Pause video ' driver.execute_script("arguments[0].pause()", video) ...
The above has been achieved HTML5 Video screen <video> Partial testing of labels , More references HTML DOM Video object .

among arguments yes JavaScript Built in objects for . Because will video Object passed to arguments, therefore arguments[0] amount to JavaScript Scripted document.getElementsByTagName("video").JavaScript Overloading is not supported , use arguments Object can simulate the effect of function overloading .

08,WebDriver Unable to operate Windows control

Common uploading and downloading of files ( reference resources How to auto save files using custom Firefox profile ?), Can pass .
.send_keys(' Local path ') and find_element_by_partial_link_text(' Download link name ').click() realization .

resolvent :

For plugin upload , Action required Windows Control's , You can install AutoIt tool , Script , Save as “.au3” file , convert to “.exe” file , Then automated script
os.system("D:\\upfile.exe") Realize uploading / download .

* Although this method can solve the problem of file uploading , Download operation problems , But not recommended .
Because through python call exe The program is not there python Within the controllable range of , How long does it take , Whether the execution process is wrong , No one knows from the automated process .

09,firefox Strong security , Error reporting is not allowed for cross domain calls

Error description :

uncaught exception: [Exception... "Component returned failure code: 0x80004005
(NS_ERROR_FAILURE) [nsIDOMNSHTMLDocument.execCommand]" nsresult: "0x80004005
(NS_ERROR_FAILURE)" location:
terms of settlement :

Firefox To cancel XMLHttpRequest Cross domain restrictions ,

The first is from  about:config  Setting in signed.applets.codebase_principal_support =
true;( Address bar input about:config Ready to proceed firefox set up );

The second is in open Add code similar to the following before the code function of :
try {
   } catch (e) {      alert("Permission UniversalBrowserRead denied.");      }

If my blog is helpful to you , If you like my blog content , please “ give the thumbs-up ” “ comment ” “ Collection ” One button three times !

Last basic knowledge ,Linux necessary ,Shell, Principles of Internet program ,Mysql database , Special topic of bag capturing tools , Interface test tools , Advanced test -Python programming ,Web automated testing ,APP automated testing , Interface automation test , Test advanced continuous integration , Test architecture development test framework , performance testing , Supporting learning resources such as safety testing 【 free 】.