I location
1.xpath positioning
If an attribute cannot uniquely distinguish an element, we can also use logical operators to connect multiple attributes to find elements
<input id="kw" class="su" name="ie"> <input id="kw" class="aa" name="ie"> <input id="bb" class="su" name="ie">
Here, if id is used to locate, the element names of the first line and the second line are the same; If class is used, the first line and the third line have the same name. At this time, you can use "and" to connect more attributes to uniquely identify an element
find_element_by_xpath("//input[@id='kw' and @class='su']/span/input")
2. Combined positioning in CSS positioning
find_element_by_css_selector("form.fm>span>input.s_ipt") find_element_by_css_selector("form#form>span>input#kw")
find_element_by_css_selector("form[class='fm']>span>input[class='s_ipt']") find_element_by_css_selector("form[id='form']>span>input[id='kw']")
II Mouse event
The operation methods of the mouse are encapsulated in the ActionChains class
ActionChains class provides common methods of mouse operation:
perform(): execute all storage behaviors in ActionChains
context_click(): right click
double_click(): double click
drag_and_drop(): drag
move_to_element(): mouse over
1. Right click operation
from time import sleep from selenium import webdriver from selenium.webdriver import ActionChains driver = webdriver.Chrome() driver.get("http://www.baidu.com") driver.maximize_window() right_click = driver.find_element_by_css_selector("form[id='form']>span[class='bg s_btn_wr']>input[id='su']") sleep(3) ActionChains(driver).context_click(right_click).perform() sleep(3) driver.quit()
2. Mouse over operation
from time import sleep from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait driver=webdriver.Chrome() driver.get("http://www.baidu.com") driver.maximize_window() ele = driver.find_element_by_css_selector("div[class='s-top-right s-isindex-wrap']>span[id='s-usersetting-top']") ActionChains(driver).move_to_element(ele).perform() sleep(3) xt_ele = WebDriverWait(driver, 5).until(expected_conditions.element_to_be_clickable((By.LINK_TEXT, "Advanced search"))) xt_ele.click() sleep(3) driver.quit()
3. Double click the mouse
from time import sleep from selenium import webdriver from selenium.webdriver import ActionChains driver = webdriver.Chrome() driver.get("http://www.baidu.com") driver.maximize_window() ele = driver.find_element_by_link_text("Journalism") ActionChains(driver).double_click(ele).perform() sleep(3) driver.quit()
4. Mouse drag and drop operation
# Locate the original location of the element element = driver.find_element_by_id("XX") # Locate the target location to which the element is to be moved target = driver.find_element_by_id("XX") # Drag and drop elements ActionChains(driver).drag_and_drop(element, target).perform()
III Keyboard events
# Firstly, the keys module is introduced from selenium.webdriver.common.keys import keys # Input contents in the input box driver.find_element_by_id("kw").send_keys("selenium") # Delete one m of multiple inputs driver.find_element_by_id("kw").send_keys(Keys.BACK_SPACE) # Enter spacebar + tutorial driver.find_element_by_id("kw").send_keys(Keys.SPACE) driver.find_element_by_id("kw").send_keys("course") # Ctrl+A select all the contents of the input box driver.find_element_by_id("kw").send_keys(Keys.CONTROL,'a') # Ctrl+X cuts the contents of the input box driver.find_element_by_id("kw").send_keys(Keys.CONTROL,'x') # Ctrl+V paste the contents of the input box driver.find_element_by_id("kw").send_keys(Keys.CONTROL,'v') # Use the Enter key instead of clicking driver.find_element_by_id("su").send_keys(Keys.ENTER) driver.quit()
send_keys(Keys.BACK_SPACE) delete key (BackSpace)
send_keys(Keys.SPACE)
send_keys(Keys.TAB) tab
send_keys(Keys.ESCAPE) fallback key (Esc)
send_keys(Keys.ENTER) enter
send_keys(Keys.CONTROL, 'a') select all (Ctrl+A)
send_keys(Keys.CONTROL, 'c') copy (Ctrl+C)
send_keys(Keys.CONTROL, 'x') cut (Ctrl+X)
send_keys(Keys.CONTROL, 'v') paste (Ctrl+V)
send_keys(Keys.F1)
send_keys(Keys.F12)
IV Locate a set of elements
# Find the element with type=checkbox through XPATH checkboxs = driver.find_element_by_xpath("//input[@type='checkbox']") # Find the element with type=checkbox through CSS checkboxs = driver.find_element_by_css_selector("input[type=checkbox]") for checkbox in checkboxs: checkbox.click() time.sleep(1) # Print the number of checkbox es of type on the current page print(len(checkboxs)) # Remove the tick of the last CheckBox in the page driver.find_element_by_css_selector("input[type=checkbox]").pop().click()
The pop() method is used to get an element in the list. It defaults to the last element and returns the value of the element. What if you just want to check one of a group of elements?
pop() or pop(-1) # gets the last element in a group by default
pop(0) # gets the first element in a group by default
pop(1) # gets the second element in a group by default
V Upload file
Prepare an upfile html
<html> <head> <title>upload_file</title> </head> <body> <div class="row-fluid"> <div class="span6 well"> <h3>upload_file</h3> <input type="file" name="file"/> </div> </div> </body> </html>
Write a Python file to access the HTML address and use send_keys upload file
from time import sleep from selenium import webdriver driver = webdriver.Chrome() driver.maximize_window() file_path = "C:/Users/winuser/Desktop/upfile.html" driver.get(file_path) # Locate the upload button and add local files driver.find_element_by_css_selector("input[type='file']").send_keys("E://upfile.txt") //send_ The file referenced in keys brackets is the address of the file to be uploaded. This is upfile Txt content can be empty, after all, just look at the upload effect sleep(3) driver.quit()
The effect picture after uploading is as follows:
Vi Download File
Automatic download of files in specified directory
from time import sleep from selenium import webdriver option = webdriver.ChromeOptions() # default_ content_ settings. Setting popups to 0 disables pop ups prefs = {'profile.default_content_settings.popups': 0, 'download.default_directory': 'E:\\'} # add_experimental_option refers to adding experimental setting parameters option.add_experimental_option('prefs', prefs) driver = webdriver.Chrome(chrome_options=option) driver.get("http://pypi.python.org/pypi/selenium") driver.maximize_window() sleep(3) driver.find_element_by_id("files-tab").click() sleep(5) driver.find_element_by_link_text("selenium-3.141.0-py2.py3-none-any.whl").click() sleep(10) driver.quit()
VII Operation cookie
from selenium import webdriver driver = webdriver.Chrome() driver.get("http://www.youdao.com") driver.maximize_window() # Get cookie information cookie = driver.get_cookies() # Print cookie information print(cookie) driver.quit()
Execution result:
After knowing the storage form of cookies, we can write cookie information to the browser in this form
from selenium import webdriver driver = webdriver.Chrome() driver.get("http://www.youdao.com") # Add cookie information driver.add_cookie({'name': 'key-1', 'value': 'value-2'}) for cookie in driver.get_cookies(): print("%s--%s" % (cookie['name'], cookie['value'])) driver.quit()
Execution result:
VIII Call JavaScript
Call JavaScript to adjust the position of the browser wheel bar
from time import sleep from selenium import webdriver driver = webdriver.Chrome() driver.get("http://baidu.com") # Sets the size of the browser window driver.maximize_window() # driver.set_window_size(1200, 1200) # search driver.find_element_by_id("kw").send_keys("selenium") driver.find_element_by_id("su").click() sleep(3) # Set the position of the browser scroll bar through JavaScript js = "window.scrollTo(100,450);" driver.execute_script(js) sleep(3) driver.quit()
Operation results:
IX Processing of verification code
from random import randint # Generate a random integer from 10000 to 99999 verify = randint(10000, 99999) print(u"Generated random number:%d" %verify) number = input("Please enter a random number:") print(number) number = int(number) if number == verify: print("Login succeeded!") elif number == 12345: print("Login succeeded!") else: print("Login failed. The verification code is entered incorrectly...")
Execution result: