By.CSS_SELECTOR
# 导包 from selenium import webdriver from selenium.webdriver.common.by import By from time import sleep from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 浏览器驱动 driver=webdriver.Chrome() driver.get(r"D:\XXX\myself\1.html") sleep(3) # 寻找元素 点击 # 等找到元素再执行 element=WebDriverWait(driver,10)
.until(EC.visibility_of_element_located((By.CSS_SELECTOR,"#ls_username"))) element.send_keys("fqs") # driver.find_element(By.NAME,"username").send_keys("fqs") # 退出 sleep(2) driver.quit()
解释
html
------------------------------------------------------------------
进阶版 基础语法
标签 #id class
# 等找到元素再执行 element=WebDriverWait(driver,10)\ .until(EC.visibility_of_element_located((By.CSS_SELECTOR,"input#ls_username.pn.vm")))
-----------------------------------------------------------------------------------
1:
属性 严格等于
标签【属性='属性值'】比如 input[id='ls_username']
# 等找到元素再执行 element=WebDriverWait(driver,10)\ .until(EC.visibility_of_element_located((By.CSS_SELECTOR,"input[id='ls_username']")))
2:
属性 以某某 开头
标签【属性^='属性值的开头部分'】 比如 input[id^='ls_u']
# 等找到元素再执行 element=WebDriverWait(driver,10)\ .until(EC.visibility_of_element_located((By.CSS_SELECTOR,"input[id^='ls_u']")))
3:
属性 以某某 结尾
标签【属性$='属性值的结尾部分'】比如 input[id$='username']
# 账号<input type="text" name="username" id="ls_username" class="pn vm"><br><br> element=WebDriverWait(driver,10)\ .until(EC.visibility_of_element_located((By.CSS_SELECTOR,"input[id$='username']")))
4:
属性 包含 某某
标签【属性*='属性值部分】比如 input[id*='username']
# 账号<input type="text" name="username" id="ls_username" class="pn vm"><br><br> element=WebDriverWait(driver,10)\ .until(EC.visibility_of_element_located((By.CSS_SELECTOR,"input[id*='username']")))