1. XPath attribute positioning
XPath can be positioned through the attributes of the element ID, name, class, as follows:
driver.find_element_by_xpath("//*[@id=‘kw‘]").send_keys("by_xpath")driver.find_element_by_xpath("//*[@name=‘wd‘]").send_keys("by_xpath")driver.find_element_by_xpath("//*[@class=‘s_ipt‘]").send_keys("by_xpath")
2. XPath other attribute positioning
driver.find_element_by_xpath("//*[@autocomplete=‘off‘]").send_keys("by_xpath")
3. XPath tags
When the same property has the same name, you can specify a label that is more accurate, as follows:
driver.find_element_by_xpath("//input[@id=‘kw‘]").send_keys("by_xpath")
4. XPath hierarchy
If the attribute of an element is not obvious, it can be found through the parent element, if the parent element's property is not very obvious, by the parent element's parent element, that is, the grandfather element, as follows
# 通过父元素定位driver.find_element_by_xpath("//span[@id=‘s_kw_wrap‘]/input").send_keys("by_xpath")#通过爷爷元素定位driver.find_element_by_xpath("//form[@id=‘form‘]/span/input").send_keys("by_xpath")
5. XPath index
If an element its sibling element is the same as its tag, this time cannot be positioned through the hierarchy, the index can be positioned as follows:
driver.find_element_by_xpath("//select[@id=‘nr‘]/option[1]").click()driver.find_element_by_xpath("//select[@id=‘nr‘]/option[2]").click()driver.find_element_by_xpath("//select[@id=‘nr‘]/option[3]").click()
The index here starts at 1, not the same as the Python index.
6. XPath Logic operations
XPath is supported with (and), or (or), non (not), as follows:
driver.find_element_by_xpath("//*[@id=‘kw‘ and @autocomplete=‘off‘]").send_keys("by_xpath")
7. XPath Fuzzy matching
# 匹配文字driver.find_element_by_xpath("//*[contains(text(), ‘hao123‘)]").click()# 匹配属性driver.find_element_by_xpath("//*[contains(@id, ‘kw‘)]").click()# 匹配以什么开头driver.find_element_by_xpath("//*[starts-with(@id, ‘s_kw_‘)]").click()# 匹配以什么结尾driver.find_element_by_xpath("//*[ends-with(@id, ‘kw_wrap‘)]").click()
Selenium + Python (3)--XPath positioning