有些HTML頁面中的元素中屬性較少,常常有找不到id、class、name等經常使用屬性的時候,這個時候xpath、css就能很好的識別到咱們的元素。css
Firefox和chrome瀏覽器中均有xpath、css插件工具。chrome
如下爲經過xpath方法寫的測試用例:瀏覽器
1 def test_xpath(self): 2 u'''採用xpath識別元素''' 3 self.browser.find_element_by_xpath(".//*[@id='kw']").send_keys("xpath test") #採用id,.//input[@id='kw'] 4 self.browser.find_element_by_xpath(".//*[@id='su']").submit() #採用id 5 log.info("採用xpath識別頁面中的屬性,[id]") 6 time.sleep(1) 7 self.browser.find_element_by_xpath(".//*[@name='wd']").clear() # 清空原關鍵字 #採用name,.//input[@name='wd'] 8 self.browser.find_element_by_xpath(".//*[@class='s_ipt']").send_keys("selenium auto test") #採用class,.//input[@class='s_ipt'] 9 #self.browser.find_element_by_xpath(".//*[@type='submit']").submit() #採用type,.//input[@type='submit'] 10 self.browser.find_element_by_xpath("//form[@id='form']/span/input[@value='百度一下']").submit() #提交搜索 11 log.info("採用xpath識別頁面中的屬性,[class、type]") 12 ''' 13 .//*[@id='kw'] 14 .//*[@name='wd'] 15 .//*[@class='s_ipt'] 16 .//*[@autocomplete='off'] 17 .//*[@type='submit'] 18 .//input[@autocomplete='off'] 19 .//input[ @ type = 'submit'] 20 //form[@id='form']/span/input[@value='百度一下'] 21 '''