Selenium automates UI

\u674e\u80b2\u6b22 2021-11-25 14:31:28

One . The first script

1. Code implementation

# coding = utf-8
from selenium import webdriver
import time
browser = webdriver.Firefox()
time.sleep(3)
browser.get("http://www.baidu.com")
time.sleep(3)
browser.find_element_by_id("kw").send_keys("selenium")
time.sleep(3)
browser.find_element_by_id("su").click()
browser.quit()

2. Script parsing

  • coding = utf-8
    Prevent confusion code .
  • from selenium import webdriver
    Want to use selenium Of webdriver The function in , First, lead the bag in
  • browser = webdriver.Firefox()
    Manipulation Firefox browser .browser You can take it .
  • browser.find_element_by_id(“kw”).send_keys(“selenium”)
    A control has several properties id 、name、( It can also be positioned in other ways ), Baidu input box id It's called kw , I'm going to type in
    selenium .
  • browser.find_element_by_id(“su”).click()
    The search button is id It's called su , I need to click the button ( click() ).
  • browser.quit()
    Exit and close every relevant driver in the window .
  • browser.close()
    Close the current window .

close Method to close the current browser window ,quit Method not only closes the window , And I'm going to quit completely webdriver, Release and driver server Connection between . So to put it simply quit Is more thorough close,quit Will better release resources

Two . Positioning of elements

#coding=utf-8
from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get("http://www.baidu.com")
######### Positioning method of Baidu input box ##########
# adopt id Way positioning 
browser.find_element_by_id("kw").send_keys("selenium")
# adopt name Way positioning 
browser.find_element_by_name("wd").send_keys("selenium")
# adopt tag name Way positioning 
browser.find_element_by_tag_name("input").send_keys("selenium") # Can't succeed , because input Too many, not the only .
# adopt class name Way positioning 
browser.find_element_by_class_name("s_ipt").send_keys("selenium")
# adopt CSS Way positioning 
browser.find_element_by_css_selector("#kw").send_keys("selenium")
# adopt xphath Way positioning 
browser.find_element_by_xpath("//*[@id='kw']").send_keys("selenium")
############################################
browser.find_element_by_id("su").click()
time.sleep(3)
browser.quit()
Please bring the original link to reprint ,thank
Similar articles