from selenium.webdriver.common.by import By ''' # 如百度输入框 <input id="kw" name="wd" class="s_ipt" value="" maxlength="255" autocomplete="off"> ''' # css_loc = (By.CSS_SELECTOR,"标签.class>子标签.class1.class2[属性名1='属性值1'][属性名2='属性值2']") # css选择器参考 https://www.w3school.com.cn/cssref/css_selectors.asp # xpath = (By.XPATH,"//标签[@属性='属性值']/子标签[@属性1='属性值1' and @属性2='属性值2']") # id定位 id_loc = (By.ID,"kw") css_loc = (By.CSS_SELECTOR,"#kw") css_loc = (By.CSS_SELECTOR,"input#kw") xpath_loc = (By.XPATH,"//input[@id='kw']") # class定位 css_loc = (By.CSS_SELECTOR,".s_ipt") css_loc = (By.CSS_SELECTOR,"input.s_ipt") xpath_loc = (By.XPATH,"//input[@class='s_ipt']") # 属性等于某个值 css_loc = (By.CSS_SELECTOR,"input[name]") # 仅有属性名没有值 css_loc = (By.CSS_SELECTOR,"input[name='wd']") css_loc = (By.CSS_SELECTOR,"input[name='wd'][autocomplete='off']") # 多个属性 xpath_loc = (By.XPATH,"//input[@name='wd' and @autocomplete='off']") # 多个属性 可使用逻辑运算符 -- and、or # 属性包含某个值 css_loc = (By.CSS_SELECTOR,"input[name*='wd']") xpath_loc = (By.XPATH,"//input[contains(@name ,'wd')]") # 属性以某个值开头 css_loc = (By.CSS_SELECTOR,"input[name^='wd']") xpath_loc = (By.XPATH,"//input[starts-with(@name,'wd')]") # 属性以某个值结尾 css_loc = (By.CSS_SELECTOR,"input[name$='wd']") xpath_loc = (By.XPATH,"//input[ends-with(@name,'wd')]") # xpath查到这种写法,实际使用不支持 # 其他定位方式 # 属性值由空格分隔,匹配其中一个值的方法 css_loc = (By.CSS_SELECTOR,"input[name~='wd']") # 属性值被-分隔 css_loc = (By.CSS_SELECTOR,"input[name|='wd']") # 文本等于或包含某个值 css_loc = (By.CSS_SELECTOR,"input:contains('nicole')") # css查到这种写法,实际使用不支持 xpath_loc = (By.XPATH,"//input[text(),'nicole']") xpath_loc = (By.XPATH, "//input[contains(text(),'nicole')]") xpath_loc = (By.XPATH, "//input[contains(.,'nicole')]") # 定位子节点 css_loc = (By.CSS_SELECTOR,"div>input") xpath_loc = (By.XPATH, "//div/input") xpath_loc = (By.XPATH, "xpath =//div//input") # 相对路径 # 定位兄弟节点 css_loc = (By.CSS_SELECTOR,"div+div") # 定位父节点 xpath_loc = (By.XPATH, "xpath =//div[@id='name']/..")