SoFunction
Updated on 2024-11-18

A summary of Python's commonly used Get Element Driver.

1, in Windows set temporary environment variables cmd command window, type path=%path%;E:\soft\python-3.5.2-embed-win32

For permanent configuration, find path under System Variables and add the Python installation directory at the end of Path.

D:\Python34, also in PATHEXT add .PY;.PYM

Then, typing python brings up the version information and it works.

2, CMD command window, the method of clearing the screen

 import os
 ('cls')

If don't return the value 0 is:

 import os
 i=('cls')

3、View the current system time

import time
 #-*-format time format-*-
localtime = ( (()) )
 #-*-Format time format [formatted as 2009-03-20 11:45:39]-*-
("%Y-%m-%d %H:%M:%S", ())
 #-*-Format time format [timestamp format]-*-
("%a %b %d %H:%M:%S %Y", ())
 #-*-Output formatted time-*-
print ("Local time is :", localtime)

4, in the CMD command line, type "python" + "space", that is, "python"; will have been written script file drag and drop to the current cursor position, the and then hit enter to run it

5. Reason for the garbled code:

Because your file is declared as utf-8 and it should also be a source file saved with utf-8 encoding. But the local default encoding for windows is cp936, which is the gbk encoding, so in the console

Printing the utf-8 string directly is of course garbled.

Solution:

It's ok to use a transcoding where the console prints, write it like this when you print it:

 print ('UTF-8').encode('GBK') 

A more generalized approach would be:

 import sys
 type = ()
 print ('UTF-8').encode(type)
 
 
 #-*-coding:UTF-8-*- or import sys
 reload(sys)
 ('UTF-8')

6, in fact, to drive the chrome browser must rely on the Chromedriver file to work.

download address:

/p/chromedriver/downloads/list

After you find the right package for your system, download and extract the chromedriver file and copy it to the root directory of your java project. Take this tutorial as an example, we will copy the chromedriver file directly to the root directory of the HelloSelenium project, which is the HelloSelenium directory. This will allow us to run it directly.

7. Install pyse : Clone it locally, and put the pyse directory into the... \Python27\Lib\site-packages\ directory.

/defnngj/pyse

python install installs

java -jar selenium-server-standalone-3.4. -multiWindow

8、Positioning properties

######### How to locate Baidu's input box ##########
 
 #Localize by id
 browser.find_element_by_id("kw").send_keys("selenium")
 
 #Localize by name
 browser.find_element_by_name("wd").send_keys("selenium")
 
 #Locate by tag name
 browser.find_element_by_tag_name("input").send_keys("selenium")
 
 #Locate by class name
 browser.find_element_by_class_name("s_ipt").send_keys("selenium")
 
 # Positioning by way of CSS
 browser.find_element_by_css_selector("#kw").send_keys("selenium")
 
 #Locate by xphan
 browser.find_element_by_xpath("//input[@id='kw']").send_keys("selenium")
 
 ############################################
 
 browser.find_element_by_id("su").click()
 (3)
 ()

I. Positioning of elements

The 8 methods provided for positioning page elements:

id/name/class name/tag name/link text/partial link text/xpath/css selector

which python corresponds to 8 methods:

 find_element_by_id()      as if: find_element_by_id("kw") 
 find_element_by_name()      as if: find_element_by_name("wd")
 find_element_by_class_name()    as if: find_element_by_class_name("s_ipt") 
 find_element_by_tag_name()     as if: find_element_by_tag_name("input") 
 find_element_by_link_text()    as if:find_element_by_link_text(u"News.") 
 find_element_by_partial_link_text()  as if:find_element_by_partial_link_text(u"A very long one.") 
 find_element_by_xpath()     as if: find_element_by_xpath(" .//*[@id='kw']") 
 find_element_by_css_selector()    as if: find_element_by_css_selector("#kw")

II. Browser control

1. Control the browser size:

set_window_size() e.g. driver.set_window_size(400,500)

maximize_window() e.g. driver.maximize_window() # no arguments

2. Browser backward, forward: back()-backward, farward()-forward

III. Mouse events

Common methods provided by the ActionChains class:

1.1 perform(): perform all the behaviors stored in ActionChains, submit the whole event

1.2 context_click(): right-click

As:

   from .action_chains import ActionChains
    ...
   ActionChains(dr).context_click(docfile).perform()

1.3 double_click(): double-click

As:

   from .action_chains import ActionChains
    ...
   doubleClick=dr.find_element_by_id("xxx")
   ActionChains(dr). double_Click(doubleClick).perform()  

1.4 drag_and_drop(source,target): dragging

As:

   from .action_chains import ActionChains
    ...
   dsource=dr.find_element_by_id("xxx")  # Dragged source element
   dtarget=dr.find_element_by_id("xxx")  # Targeted target elements released
   ActionChains(dr).drag_and_drop(dsource,dtarget).perform()
  

1.5 move_to_element(): mouse hover

As:

   from .action_chains import ActionChains
    ...
   above=dr.find_element_by_id("xxx")
   ActionChains(dr).move_to_element(above).perform()

IV. Keyboard events

1. First of all, import the package of keyboard events

from  importKeys
 ...
 ("")
 # Input content
 dr.find_element_by_id("kw").send_keys("seleniumm")
 # Delete the last letter of the input.
 dr.find_element_by_id("kw").send_keys(Keys.BACK_SPACE)
 # Input: space + tutorial
 dr.find_element_by_id("kw").send_keys()
 dr.find_element_by_id("kw").send_keys(u"Tutorial.")
 #ctrl+a selects the contents of the input box in full
 dr.find_element_by_id("kw").send_keys(,'a')
 #ctrl+x cut and paste the contents of the input box
 dr.find_element_by_id("kw").send_keys(,'x')
 #ctrl+v cut and paste the contents of the input box
 dr.find_element_by_id("kw").send_keys(,'v')
 #Enter key operation
 dr.find_element_by_id("su").send_keys()
 ()
 

Common keyboard operations are organized:

 send_keys(Keys.BACK_SPACE) #Delete key BackSpace
 send_keys()  #Space
 send_keys()   #Tab
 send_keys()  #Back button Esc
 send_keys()  #ReturnEnter
 send_keys(,'a') #Ctrl+a
 send_keys(,'c') #Ctrl+c 
 send_keys(,'x') #Ctrl+x
 send_keys(,'v') #Ctrl+x
 send_keys(Keys.F1)   #F1,SimilarlyF1-F12

V. Access to validation

VI. Setting up the wait

1. display wait: wait for a condition is established, continue to execute, otherwise the maximum waiting time to reach the exception: TimeoutException, display wait for the current to locate the element using the

WebDriverWait(driver, timeout,poll_frequency,ignored_exceptions=None).until(method,message) 

Example:

 WebDriverWait(dr,5,0.5,None).until(
  expected_conditions.presence_of_element_located((,"kw1")),message='test') 

Explanation:

():During the setup time,By default, the current page element is checked for existence once in a while.,Throws an exception if it cannot be detected beyond the current specified time.;
 :webdriverBrowser Driver,ie、firefox、chromea
 :Maximum timeout,in seconds
 D.poll_frequency:Sleep interval-pacemaker,default (setting)0.5unit of angle or arc equivalent one sixtieth of a degree
 E.ignored_exceptions:Exception message after timeout,default (setting)抛出NoSuchElementExceptionexceptions
 (method,message): Calling this method provides the driver as a parameter,Until the return value isTrue
 G.until_not(method,message):Calling this method provides the driver as a parameter,Until the return value isFalse
 H.expected_conditionsThe expected conditional realizations provided by the class are:
  title_is:Determine if the title isxx
  title_contains:Determine if the title containsxx
  presence_of_element_located:Whether the element exists
 
  visibility_of_element_located:Whether the element exists
 
  visibility_of:visibility
 
  presence_of_all_elements_located:判断一组Whether the element exists
 
  text_to_be_present_in_element:Determine whether an element hasxxtext message 
 
  text_to_be_present_in_element_value:Determine if the element value hasxxtext message 
 
  frame_to_be_available_and_switch_to_it:表单visibility,and switch to that form
 
  invisibility_of_element_located:Determine if an element is hidden
  element_to_be_clickable:Determine if an element is clicked,It is visible and activated
  staleness_of:Wait until an element is no longer attached to theDOM
  element_to_be_selected:selected element
  element_located_to_be_selected:A desired element is located in the selected
  element_selection_state_to_be:An expectation checks if the given element is selected.
  element_located_selection_state_to_be:Expect to find an element and check if it is a selection state
  alert_is_present:Expect a warning message 

2. Implicit wait: wait for a certain amount of time for all the elements of the page to finish loading, which element exceeds the set length of time is not loaded on the exception NoSuchElementException, implicitly waiting for all the elements of the

implicitly_wait(5) #Default unit is seconds

Example:

dr.implicitly_wait(5)

VII. sleep hibernation mandatory program wait in python

 from time import sleep
 sleep(4) #Default unit seconds,Setting less than1The time in seconds can be expressed as a decimal point such assleep(0.6)

Eight, locate a group of elements, similar to the method of locating a single element in the 1

 find_elements_by_id()      as if: find_elements_by_id("kw") 
 find_elements_by_name()     as if: find_elements_by_name("wd")
 find_elements_by_class_name()    as if: find_elements_by_class_name("s_ipt") 
 find_elements_by_tag_name()    as if: find_elements_by_tag_name("input") 
 find_elements_by_link_text()    as if:find_elements_by_link_text(u"News.") 
 find_elements_by_partial_link_text()  as if:find_elements_by_partial_link_text(u"A very long one.") 
 find_elements_by_xpath()     as if: find_elements_by_xpath(" .//*[@id='kw']") 
 find_elements_by_css_selector()   as if: find_elements_by_css_selector("#kw")

Usage Scenarios:

a. Batch operation objects, such as checking all checkboxes on the page

b. First get a group of objects, and then in this group of objects to locate the need for a number of objects, such as locating all the checkboxes, and then select the last one

For example, the code is as follows

Page:

 <styletype="text/css">
 body{font-size:12px; font-family:Tahoma;}
 .checkbox{vertical-align:middle; margin-top:0;}
 </style>
 <body>
 <inputclass="checkbox"type="checkbox"/>New Year's Day
 <inputtype="checkbox"name="test"/>Christmas time
 <inputtype="checkbox"name="test"/>online broker
 <inputtype="checkbox"name="test"/>Avatar (movie)
 <inputtype="checkbox"name="test"/>October Siege
 <inputtype="checkbox"name="test"/>water price hike
 <inputtype="button"value="Testing."/>
 </body>

python code:

from selenium import webdriver
  
  dr=()
  ("D:\\workspace\\pySelenium\\resources\\")
 # Use the tagname method to select all elements on the page whose tagname is input.
 select_tagname=dr.find_elements_by_tag_name("input")
 # Use xpath to select all elements on the page whose tagname is input.
 select_xpath=dr.find_elements_by_xpath("//input[@type='checkbox']")
 # Use css_select to select all elements on the page whose tagname is input.
 select_css=dr.find_elements_by_css_selector('input[type=checkbox]')
 for i in select_tagname:
 # Loop over each input element and click to select it.
 if i.get_attribute("type")=='checkbox':
 ()
 for j in select_xpath:
 # Loop over each input element to perform a click-cancel operation.
 ()
 for k in select_css:
 # Loop over each input element and click to select it.
 ()
 # Print out the number of checkboxes
 print'The number of checkboxes on the ---- page is:',len(select_css)
 # Use pop() to get the first element of a group of 1 elements
 select_css.pop(0).click()#First
 select_css.pop(1).click()#The second one #
 select_css.pop().click()# The last one
 select_css.pop(-1).click()# The last one
 select_css.pop(-2).click()# Penultimate
 ()

Remarks: pop(): select one of a group of elements, it should be noted that: pop() and pop(-1) both indicate the last element

Nine, multi-form switching (for the operation of a frame nested form)

Frame page:

<html>
<body>
<frameset>
<h3>frame</h3>
<iframeid='frameid'name='frameName'width="800"height="500"src=""/>
</frameset>
</body>
</html>

python code:

 ("D:\\workspace\\pySelenium\\resources\\")
 dr.switch_to_frame("frameid")#Enter the iframe via the frame's id
 #dr.switch_to_frame("frameName") #Go to iframe via frame's name
 # Now you can manipulate the frames
 dr.find_element_by_id("kw").send_keys("selenium")
 dr.find_element_by_id("su").click()
 dr.switch_to_default_content()#Log out of the currentframeReturn to previous level

Remarks:

1. switch_to_frame() defaults to switching directly from the id or name attribute of the form.

2. After the completion of the current frame form operation, you can switch_to_default_content () method to return to the previous layer of the form, that is, from the nearest switch_to_frame () method

3. For the frame without id and name attributes through the following way to enter the frame (positioning to the frame to the page object to pass)

python code:

 ("D:\\workspace\\pySelenium\\resources\\")
  #Locate to frame page element
  framepath=dr.find_element_by_class_name("frameClassname")
  dr.switch_to_frame(framepath)# Go to iframe via frame page object
 # Now you can manipulate the frames
 dr.find_element_by_id("kw").send_keys("selenium")
 dr.find_element_by_id("su").click()
 dr.switch_to_default_content()#Log out of the currentframeReturn to previous level

X. Multi-window switching

The selenium-webdriver uses the switch_to_window() method to switch between arbitrary windows, commonly used methods are

driver.current_window_handle # Get the current window handle
driver.window_handles # Return all window handles to the current session
driver.switch_to_window() #Access window,For switching between different windows

python code:

("")
 current_handle=dr.current_window_handle #Get Baidu Home Window Handle
 index_login=dr.find_element_by_xpath("//div[@id='u1']/a[@class='lb']")# Get Login Button Object
 index_login.click()#Click to log in
 dr.implicitly_wait(5)
 dr.find_element_by_class_name("pass-reglink").click()#Click the Register Now button
 all_handles=dr.window_handles # Get handles to all open windows
 for handle in all_handles:
 if handle==current_handle:
 dr.switch_to_window(handle)
 '''
 ... Manipulating the Home Window
 '''
 print'----Home Pagetitle:',
 for handle in all_handles:
 if handle!=current_handle:
 dr.switch_to_window(handle)
 '''
 ... Manipulating the Registration Window
 '''
 print'----registration pagetitle:',

XI. Warning box processing

The webdriver handles js-generated alert, confirm, and prompt by using switch_to_alert() to locate alert/confirm/prompt, and then using text, accept, disable, and send_keys to manipulate as needed.

text: return text information in alert, confirm, prompt

accept: Click on the Confirm button

dismiss: click on the cancel button

send_keys: input value when there is a dialog box in alert, confirm.

python code:

 ("")
 set_link=dr.find_element_by_xpath("//div[@id='u1']/a[@class='pf']")#Find the setup link element
 ActionChains(dr).move_to_element(set_link).perform()# Mouse over settings
 dr.find_element_by_xpath("//a[@class='setpref']").click()#Click on the Search Settings link
 (3) # Add wait time etc. buttons are available, otherwise an error will be reported.
 save_set=dr.find_element_by_css_selector("#gxszButton > ")#Get the save settings button
 save_set.click()# Click the Save Settings button
  
 alert=dr.switch_to_alert()     #Go to alert
 print'---- The content in the pop-up alert reads:', # Print the text contents of the dialog box
 ()# Click the OK button in the alert in the dialog box.
 #() #Click the cancel button in the dialog box
 #alert.send_keys("What was entered in the dialog box") #Enter the content in the dialog box

XII. Uploading documents

There are 2 types: normal upload, plug-in upload

Normal upload: put the path of a local file as a value in the input tag, and pass the value to the server when submitting via a form.

Plugin upload: refers to the upload function or plugin realized based on flash, javascript or ajax technology.

1. Use send_keys for normal uploads.

python code:

("D:\\workspace\\pySelenium\\resources\\")
 loadFile=dr.find_element_by_name("filebutton")# Get the uploaded file input element node
 loadFile.send_keys("D:\\workspace\\pySelenium\\resources\\")#Enter the address of the uploaded file to realize the upload

2. Plug-in upload: using AutoIt to achieve, - need to install AutoIt program

AutoIt installation, the use of temporary omitted, need to be added, the process is: AutoIt write upload file script to generate exe file, in python script to call

python code:

 loadFile=dr.find_element_by_name("filebutton")# Get Upload Button
 () # Click the upload button to bring up the upload dialog box
 ("D:\\") #call (programming)autoItgeneratedexefile,Realization of the import

Thirteen, download the file: the use of AutoIt to achieve, - the need to install AutoIt program, the same method of uploading

python code:

 ffp=()
 ffp.set_preference("",2)#0: means download to the default path of the browser; 2: download to the specified directory
 ffp.set_preference("",False)#Whether to show the start: True: show; False: don't show
 ffp.set_preference("", ())# Specify the directory of the downloaded file, () no parameter, return to the current directory
 # ffp.set_preference("", "application/octet-stream") # download file type.
 # Specify the value of the content-type of the download page, application/octet-stream for the file type, http-content-type commonly used cross-reference table search Baidu
 dr=(firefox_profile=ffp)
 ("/pypi/selenium#downloads")
 dr.find_element_by_xpath("//div[@id='content']/div[3]/table/tbody/tr[3]/td[1]/span/a[1]").click()
 # Next use autoIt to implement
 

XIV. Cookies operation

The webdriver's method for manipulating cookies:

get_cookies(): get the value of all cookies

get_cookie(name): get information about a cookie with a specific name value

add_cookie(cookie_dict): add cookie, must have name and value

delete_cookie(name): deletes cookie information for a specific name, finds the specific cookie by name and deletes it

delete_all_cookies(): deletes information about all cookies in the browser

Attention:

is stored as a dictionary;

2. Usage scenarios: such as login function will write the user name into the browser cookie to specify the key for username, then you can get_cookies () to find username, print the value, can not find the instructions to save the browser's cookie is a bug.

python code:

 num=1
 ("")
 cookies=dr.get_cookies()# Get all the information about the cookie
 for ck in cookies:
 print'---- all cookies',num,':',ck #Print all information about the cookie
 num=num+1
 print'---- looks up cookies by name:',dr.get_cookie("PSTM")# Get cookie information by the name of the cookie
 dr.add_cookie({'name':'hello','value':'123456789'})# Add session information to name and value
 cookies2=dr.get_cookies()#Refetch all the information from the cookie
 for ck2 in cookies2:
 if ck2['name']=='hello':
 print"Cookie information added by ----: %s-->%s",(ck2['name'],ck2['value'])

XV. javascript call, python use the method: execute_script()

python code:

("")
 dr.find_element_by_id("kw").send_keys("selenium")
 dr.find_element_by_id("su").click()
 js="var q==1000" # Scroll to the bottom
 dr.execute_script(js)
 (4)
 js2="var q==0"  # Scroll bar to top of page
 dr.execute_script(js2)

Sixteen, screenshot, applicable to the script error, the current window to save a screenshot, use the function: get_screenshot_as_file ()

python code:

 ("")
 try:
 dr.find_element_by_id("kw1").send_keys("selenium")
 dr.find_element_by_id("su").click()
 exceptNoSuchElementException,msg:
 dr.get_screenshot_as_file("d:\\") # Screenshot output to disk d
 print msg
 ()

XVII. Closing the window

quit(): Quit the relevant driver and close all windows.

close(): close the current window, can be used to close the current window when calling multiple windows.

XVIII. CAPTCHA Processing

Method 1: Remove the CAPTCHA, Problem: If you are running the script in a formal environment then there is a risk in taking it off.

Method 2: Set up a universal verification code, do not need to cancel the verification code, leave a backdoor in the program - set up a universal verification code, enter the universal verification code on the logo through the

python code:

 
 import random
 randnum=(1000,9999)
 print"---- generates random numbers as:",randnum
 input_num=input(u"Please enter the verification code:")
 print"---- Enter the CAPTCHA as:",input_num
 if input_num==randnum:
 print"Random number correct, login successful."
 elif input_num==1234:
 print"Entered correctly. Login successful."
 else:
 print"Login failed."

Method 3: Use the cookie method to get, read the cookie value of the previous login to access, direct login, do not need to verify the code

--------------------------------------------------- CMD ----------- command to start Python scripts

The file is named: 🙂 It doesn't seem to work

 @echo off
 echo.
 python E:\pythonScript\Auto_linknetwork.py
 cd /D C:\Python27
 
 rm #!C:\Python27/
 import os;
 i=("Clear the screen.",cls);
 import time;
 #-*-Format time format [formatted as 2009-03-20 11:45:39]-*-
 ("%Y-%m-%d %H:%M:%S", ());
 print ("The current time of the system is :", localtime); 

1. Screenshot

driver.save_screenshot('E:\\pythonScript\\images\\'+strTime+'')

III. WebElement interface to get the value

The WebElement interface provides access to common values that are also important. size Get the size of the element

text Get the text of the element

get_attribute(name) Get attribute value

location gets the coordinates of the element, first find the element you want to get, then call the method.

page_source Returns the page source

Return to Page Title

current_url Get the URL of the current page.

is_displayed() sets whether the element is visible or not

is_enabled() determines if the element is used.

is_selected() determines if an element is selected.

tag_name Returns the tagName of the element.

IV. Getting the return value in a function

function ()

  def returnval():
 
  driver = ()
  print u"\n return value"
  return driver
 
  #returnval()
 
  src = ("")
 
  returnval().get(src)
 
  print returnval()

Returns a function as a return value, does not return the result only the function

  def lazy_sum(*args):
   def sum():
    ax = 0
    for n in args:
     ax = ax + n
    return ax
   return sum
  >> f = lazy_sum(1, 3, 2, 7, 9)
  >> f
  >> f() 
 #This is when the function value is actually calculated;

New instance driver = ()

1. Get the Url function of the current page

Method: current_url

Example:

driver.current_url

2. Get element coordinates

Method: location

Explanation: First find the element you want to get, then call the location method

Example:

driver.find_element_by_xpath("//*[@id='tablechart']/tbody/tr[14]/td[9]").location

3. Submission of forms

Method: submit

Explanation:Find the form (from) directly call submit can be

Example:

driver.find_element_by_id("form1").submit()

4. Getting the value of a CSS property

Method: value_of_css_property(css_name)

Example:

driver.find_element_by_css_selector("").value_of_css_property("")

5. Get the value of an element's attribute

Method: get_attribute(element_name)

Example:

driver.find_element_by_id("sellaiyuan").get_attribute("sellaiyuan")

6. Determine whether an element is selected

Method: is_selected()

Example:

driver.find_element_by_id("form1").is_selected()

7. Return the size of the element

Method: size

Example:

driver.find_element_by_id("iptPassword").size

Return value: {'width': 250, 'height': 30}

8. Determine whether an element is displayed

Method: is_displayed()

Example:

driver.find_element_by_id("iptPassword").is_displayed()

9. Determine whether an element is used

Method: is_enabled()

Example:

driver.find_element_by_id("iptPassword").is_enabled()

10. Get the text value of the element

Method: text

Example: driver.find_element_by_id("iptUsername").text

11. Element Assignment

Method: send_keys(*values)

Example:

driver.find_element_by_id("iptUsername").send_keys('admin')

Note that if it is a function you need to add the escape u,eg.

driver.find_element_by_id("iptUsername").send_keys(u'Youth')

12. Returns the tagName of the element.

Method: tag_name

Example:

driver.find_element_by_id("iptUsername").tag_name

13. Delete cookies from your browser

Method: delete_all_cookies()

Example:

driver.delete_all_cookies()

14. Delete the specified cookie

Method: delete_cookie(name)

Example: deriver.delete_cookie("my_cookie_name")

15. Close the browser

Method: close()

Example: ()

16. Close the browser and launch the driver

Method: quit()

Example: ()

17. Return to previous page

Method: back()

Example: ()

18. Setting the wait timeout

Method: implicitly_wait(wait_time)

Example: driver.implicitly_wait(30)

19. Maximize browser window

Method: maximize_window()

Example: driver.maximize_window()

20. View the name of the browser

Method: name

Example:

Above this article on Python commonly used to get elements Driver Summary is all I have shared with you, I hope to give you a reference, and I hope you support me more.