Introduction to Python selenium usage

Keywords: Python Selenium Attribute Linux

# Edition
    python==3.7.3
    selenium==4.0.0a1

# selenium pypi address
https://pypi.org/project/selenium/

Catalog:
I. Initialization
2. Element Search
3. select Label Operation
4. Executing js scripts
5. iframe operation
6. Action and Action Chain
VII. Abnormal handling
VIII. Withdrawal Procedure

I. Initialization

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# The new version of webdriver.chrome specifies the driver location of Google Browser by default. If you want to customize the location, you need to instantiate a Service object.
service = Service(executable_path=revoction_config.chromedriverpath)
driver = webdriver.Chrome(service=service)
driver.implicitly_wait(5)   # Implicitly waiting for unloaded elements
driver.get('http://www.baidu.com')

# Headless mode configuration
opt = webdriver.ChromeOptions()     # Creating chrome objects
opt.add_argument('--no-sandbox')    # Enable non-sandbox mode, linux must fill
opt.add_argument('--disable-gpu')   # Disable gpu, linux deployment needs to be filled in to prevent unknown bug s
opt.add_argument('headless')        # Enable headless mode
driver = webdriver.Chrome(options=opt)
driver.implicitly_wait(5)           # Implicitly waiting for unloaded elements
driver.get('http://www.baidu.com')

II. Element Search

  1. Direct search

    # Find one at a time
    driver.find_element_by_id                    # Press id attribute
    driver.find_element_by_name                  # By name attribute
    driver.find_element_by_xpath             # Press XPath
    driver.find_element_by_link_text         # Filter by text in the < a > label
    driver.find_element_by_partial_link_text # Filter by text in the < a > label, containing the text of a string
    driver.find_element_by_tag_name              # Signature by Mark
    driver.find_element_by_class_name            # Class attribute
    driver.find_element_by_css_selector          # Find through css selector
    
    # Find multiple elements at a time (these methods return a list list)
    driver.find_elements_by_name
    driver.find_elements_by_xpath
    driver.find_elements_by_link_text
    driver.find_elements_by_partial_link_text
    driver.find_elements_by_tag_name
    driver.find_elements_by_class_name
    driver.find_elements_by_css_selector

2. Use the By method.

   # The by method is the same as the direct search method, but the writing is different.
   from selenium.webdriver.common.by import By

   driver.find_element(By.XPATH,Expression)
   //Equal to
   driver.find_element_by_xpath(Expression)

   # Find the input tag whose name attribute equals username
   driver.find_element(By.XPATH,"//input[@name='username']")

   # View the label of the name attribute beginning with user
   driver.find_element(By.XPATH,"//input[starts-with(@name='username')]")

   # If you search for multiple elements
   driver.find_elements()

3.XPath

There are two ways to search for XPath: absolute path and relative path.

  • Find the div tag with the class attribute username in body.

     # Absolute path example:
     "/html/body/div[@class='username']"
    
     # Relative path example:
     "//div[@class='username']"
  • Get all the subtags under the tbody tag.

     "/table/tbody/*"
  • Get the & lt; A & gt of class attribute username; the first tag after the tag.

     /a[@class='username']/following-sibling::li[1]
  • View the label with the name attribute beginning with user.

     "//input[starts-with(@name='username')]"

Third, select tag operation (officially called UI Support).

from selenium.webdriver.support.select import Select

# step 1: Find the select tag and instantiate it.
select_element = driver.find_element(By.XPATH,"//select[@class='address']")
select = Select(select_element)

# step 2: Select text by option
select.select_by_visible_text('Beijing')

4. Execute js script.

# For example, in the select tag, the option you want does not exist
java_scripts_text = '''d = document.getElementById('address');d.options.add(new Option("{0}","{0}"));'''.format('Beijing')

driver.execute_script(java_scripts_text)

# Then instantiate Select and select text as Beijing's option.

5. iframe operation.

If you want to manipulate the elements in iframe, you must first enter iframe.
# First find the iframe tag
i = driver.find_element(By.XPATH, "//iframe")
# Enter iframe
driver.switch_to.frame(i)
# Exit iframe
driver.switch_to.default_content()

6. Action Chains (officially called Action Chains).

  1. action

    # Enter text in the input element
    input_element = find_element(By.XPATH,"//input[@name='username']")
    input_element.send_keys('xiaoming')
    
    # Click element
    a_element = find_element(By.XPATH,"//a[@class='baidu']")
    a_element.click()
  2. Action chain

    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.common.keys import Keys
    
    # Hold down the Ctrl key and press the left mouse button to click on label a
    a_element = find_element(By.XPATH,"//a[@class='baidu']")
    
    ac = ActionChains(driver)
    
    # First move to label a, then press the left Ctrl key, then click the left mouse button, finally release the left Ctrl key, and execute the action chain.
    ac.move_to_element(a_element).key_down(Keys.LEFT_CONTROL).click().key_up(Keys.LEFT_CONTROL).perform()
    
    # Interpretation:
    key_down():     Press a key
       key_up():        Release a key
       send_keys(): Press and release a key
       click():     Single mouse left key
       perform():       Execution Action Chain

Seventh, exception handling (officially called Exceptions).

Classes for exception handling are all in selenium.common.exceptions. *. To catch selenium exceptions, you must first import the class of the object.

from selenium.common.exceptions import NoSuchElementException

try:
    a_element = driver.find_element(By.PARTIAL_LINK_TEXT, 'Baidu')
except NoSuchElementException:
    print("Can't find text For Baidu. a Label.")

8. Withdrawal procedure.

driver.quit()

Posted by greenie__ on Mon, 14 Oct 2019 09:11:13 -0700