Selenium 3
# -*- coding: UTF-8 -*-
from selenium import webdriver
CHROME_PATH = r'xxx\chrome.exe'
CHROMEDRIVER_PATH = r'xxx\chromedriver.exe'
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)
options.binary_location = CHROME_PATH
driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, options=options)
# 定位单个元素
driver.find_element_by_class_name("className")
driver.find_element_by_css_selector(".className")
driver.find_element_by_id("elementId")
driver.find_element_by_link_text("linkText")
driver.find_element_by_name("elementName")
driver.find_element_by_partial_link_text("partialText")
driver.find_element_by_tag_name("elementTagName")
driver.find_element_by_xpath("xpath")
# 定位多个元素
driver.find_elements_by_class_name("className")
driver.find_elements_by_css_selector(".className")
driver.find_elements_by_id("elementId")
driver.find_elements_by_link_text("linkText")
driver.find_elements_by_name("elementName")
driver.find_elements_by_partial_link_text("partialText")
driver.find_elements_by_tag_name("elementTagName")
driver.find_elements_by_xpath("xpath")
Selenium 4
# -*- coding: UTF-8 -*-
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
CHROME_PATH = r'xxx\chrome.exe'
CHROMEDRIVER_PATH = r'xxx\chromedriver.exe'
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("useAutomationExtension", False)
options.binary_location = CHROME_PATH
service = Service(executable_path=CHROMEDRIVER_PATH)
driver = webdriver.Chrome(service=service, options=options)
# 定位单个元素
driver.find_element(By.CLASS_NAME, "xx")
driver.find_element(By.CSS_SELECTOR, "xx")
driver.find_element(By.ID, "xx")
driver.find_element(By.LINK_TEXT, "xx")
driver.find_element(By.NAME, "xx")
driver.find_element(By.PARITIAL_LINK_TEXT, "xx")
driver.find_element(By.TAG_NAME, "xx")
driver.find_element(By.XPATH, "xx")
# 定位多个元素
driver.find_elements(By.CLASS_NAME, "xx")
driver.find_elements(By.CSS_SELECTOR, "xx")
driver.find_elements(By.ID, "xx")
driver.find_elements(By.LINK_TEXT, "xx")
driver.find_elements(By.NAME, "xx")
driver.find_elements(By.PARITIAL_LINK_TEXT, "xx")
driver.find_elements(By.TAG_NAME, "xx")
driver.find_elements(By.XPATH, "xx")