selenium 常用的选择器
新版本Selenium代码需要引入:
from selenium.webdriver.common.by import By
选择器也变了,而后做如下修改
# inputTag = driver.find_element_by_id("value") # 利用ID查找 # 改为: inputTag = driver.find_element(By.ID, "value") # inputTags = driver.find_element_by_class_name("value") # 利用类名查找 # 改为: inputTag = driver.find_element(By.CLASS_NAME, "value") # inputTag = driver.find_element_by_name("value") # 利用name属性查找 # 改为: inputTag = driver.find_element(By.NAME, "value") # inputTag = driver.find_element_by_tag_name("value") # 利用标签名查找 # 改为: inputTag = driver.find_element(By.TAG_NAME, "value") # inputTag = driver.find_element_by_xpath("value") # 利用xpath查找 # 改为: inputTag = driver.find_element(By.XPATH, "value") # inputTag = driver.find_element_by_css_selector("value") # 利用CSS选择器查找 # 改为: inputTag = driver.find_element(By.CSS_SELECTOR, "value")
下面是全部代码:
# 1.导入 from selenium.webdriver.chrome.service import Service from selenium import webdriver from selenium.webdriver.common.by import By # 2. 创建浏览器操作对象 path = Service('chromedriver.exe') browser = webdriver.Chrome(service=path) # 3 访问网站 url = 'https://www.baidu.com' browser.get(url) # button = browser.find_element(By.ID,'su') #通过id来查找 button = browser.find_element(By.CSS_SELECTOR,'#su') #通过css选择器来查找 我喜欢用这个 # button = browser.find_element(By.XPATH,'//*[@id="su"]') #通过XPATH来查找 print(button) input('input阻止浏览器退出')
这三种最常用