Basic use of Python selenium webdriver

 Common examples of selenium webdriver

 

foreword

This article introduces the common content of Selenium: understand what Selenium Webdriver does


The following is the body of this article, the following case for reference 

1. Pip installation & creation of Bowser object

1. Pip install selenium

pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple

2. Create Bowser object

# Importing the webdriver module
from selenium import webdriver

# Specify the Chrome browser to use
driver = webdriver.Chrome()  # chrome_options,executable_path These two parameters are commonly used

Second, webdriver.ChromeOptions configuration

Common modes for configuring browsers

Common functions of chromeoptions
(1) Add startup parameters (add_argument)
(2) Add extension application parameters (add_extension, add_encoded_extension), commonly used in proxy authentication
(3) Add experimental parameters (add_experimental_option) The
code is as follows (example):

options= webdriver.ChromeOptions() #Create   a configuration object 
options.add_argument( ' lang=zh_CN.UTF-8 ' )   #Set Chinese 
options.add_argument( ' --headless ' )   #Headless parameters, the browser runs in the background hidden 
options .add_argument( ' --disable-gpu ' ) #Disable GPU acceleration 
options.add_argument( ' --start-maximized ' ) #Browser maximized 
options.add_argument( ' --window-size=1280x1024 ' ) #Set the browser Resolution (window size) 
options.add_argument( '--user-agent="" ' ) #Set the User-Agent of the request header 
options.add_argument( ' --incognito ' )   #Incognito mode (incognito mode) 
options.add_argument(f ' --proxy-server={proxy } ' )   #Add IP proxy proxy=f"http://{ip}:{port}" 
#Close the prompt 'Chrome is currently controlled by automatic testing software' 
options.add_experimental_option( ' useAutomationExtension ' , False)
options.add_experimental_option( ' excludeSwitches ' , [ ' enable-automation ' ])
prefs = {
     " download.default_directory " : " D:\download " ,   #Set browser download address (absolute path) 
    " profile.managed_default_content_settings.images " : 2,   #Do not load images 
}
chrome_options.add_experimental_option( ' prefs ' , prefs)   
#add prefs # chrome_options="browser configuration parameters", executable_path="browser drive absolute path" 
driver = webdriver.Chrome(chrome_options=options " ) # create browser object 
driver. maximize_window()   #Browser window maximization 
driver.set_page_load_timeout(30) #Set   connection timeout for 30 seconds

 

3. Common codes

#Import webdriver module 
    from selenium import webdriver
    driver = webdriver.Chrome()   # chrome_options, executable_path commonly use these two parameters 
    # get will wait until the page is fully loaded before executing the next code, if it exceeds the setting of set_page_load_timeout(), an exception will be thrown. 
    driver.get( " https://baidu.com/ " )
    new_window = driver.window_handles[-1] #The    new window '-1' represents the last window opened, how many windows in the navigation bar are locked according to the subscript 
    driver.switch_to.window(new_window) #Switch   to the new window: 
    driver. switch_to.frame( ' passport_iframe ' )   #Locate to iframe according to name or id 
    driver.switch_to.default_content() #Switch   out (iframe) to default, there are many ways to switch to BaiDu 
    driver.find_element_by_xpath( ' //input[@xx ="xxxx"] ' ).send_keys(content) #Locate   element input content according to xpath syntax 
    driver.find_element_by_xpath( ' //div[@xx="xxxx"] ' ).  click() #Locate the element according to the xpath syntax and click
    driver.find_element_by_xpath( ' //div[@xx="xxxx"] ' ).text   #Get the text information of the element after positioning according to the xpath syntax 
    driver.get_cookie( ' name ' )   #Get the object of the corresponding dictionary type according to the name 
    driver. get_cookies() #Return   a list containing multiple dictionary-type objects 
    #Add Cookie part parameter introduction: name=cookie name, value=cookie corresponding value, domain=server domain name, expiry=Cookie valid expiration date 
    driver.add_cookie( { ' name ' : ' xxx ' , ' value ' : ' xxx ' })   #Add cookies
    driver.delete_cookie( ' name ' )   #delete the specified part of cookies 
    driver.delete_all_cookies() #delete   all cookies 
    js= " var q=document.documentElement.scrollTop=10000 "   #scroll to the bottom 
    js= " var q=document. documentElement.scrollTop=0 "   #Scroll to the top 
    driver.execute_script(js) #Execute   JS code, more on your own BaiDu 
    driver.quit() #Exit   the browser

 

4. Exception handling in selenium

#Import exceptions module 
from selenium.common import exceptions
 try :
     #Execute code 
except exceptions.TimeoutException:
     print ( " xxxx - request loading timeout exception!\n " , end= '' )
 except exceptions.NoSuchElementException:
        print ( " xxxx - web page Element positioning exception!\n " , end= '' )
 except exceptions.NoSuchWindowException:
     print ( " xxxx - target window switching exception!\n " , end= '' )
 exceptexceptions.WebDriverException:
        print ( " xxxx - browser object various exceptions!\n " , end= '' )
 except Exception:
     print ( " xxxx - above uncaught exceptions!\n " , end= '' )

 


Summarize

For example: the above is the content to be recorded today. This article only briefly introduces the use of selenium. Selenium provides a large number of functions and methods that enable us to realize automated testing quickly. New common operations will be recorded on the basis of this article.
Google official download address: https://www.google.cn/chrome/
Google driver download address: https://npm.taobao.org/mirrors/chromedriver/

Post a Comment (0)
Previous Post Next Post