18种定位器
selenium提供了18种定位器,方便我们找到需要的控件
- 单数定位器*8
# 1、id
element = driver.find_element_by_id('i1')
print(element)
element.send_keys("通过id定位输入的字符")
#2、class定位
element2 = driver.find_element_by_class_name("classname")
print(element2)
element2.send_keys("通过class定位输入的字符")
# 如果重复则取第一个
# 3、css selector
element3 = driver.find_element_by_css_selector("input[placeholder=\"请通过CSS SELECTOR定位元素\"]")
print(element3)
element3.send_keys("通过css selector定位输入的字符")
# 4、name的定位方式
el4 = driver.find_element_by_name("name")
el4.send_keys("通过name定位输入的字符")
# 5、通过xpath
el5 = driver.find_element_by_xpath("//input[@placeholder=\"请通过XPATH定位元素\"]")
el5.send_keys("通过xpath定位输入的字符")
# 6、tag
el6 = driver.find_element_by_tag_name("input")
el6.send_keys("通过tagname定位输入的字符")
# 7、link_text
el7 = driver.find_element_by_link_text("跳转大师兄博客地址")
el7.click()
# 8、模糊linktext
el8 = driver.find_element_by_partial_link_text("大师兄博客")
el8.click()
- 复数定位器*8
# 以id举例
# 1、id
elements = driver.find_elements_by_id('i1')
print(elements)
elements[0].send_keys("通过id定位输入的字符")
···
···
- 底层调用*2
***********进入find_element_by_id*************
def find_element_by_id(self, id_):
"""Finds an element by id.
:Args:
- id\_ - The id of the element to be found.
:Returns:
- WebElement - the element if it was found
:Raises:
- NoSuchElementException - if the element wasn't found
:Usage:
element = driver.find_element_by_id('foo')
"""
return self.find_element(by=By.ID, value=id_
*******可以看到调用了find_element方法,继续进入find_element
def find_element(self, by=By.ID, value=None):
"""
'Private' method used by the find_element_by_* methods.
:Usage:
Use the corresponding find_element_by_* instead of this.
:rtype: WebElement
"""
if self.w3c:
if by == By.ID:
by = By.CSS_SELECTOR
value = '[id="%s"]' % value
elif by == By.TAG_NAME:
by = By.CSS_SELECTOR
elif by == By.CLASS_NAME:
by = By.CSS_SELECTOR
value = ".%s" % value
elif by == By.NAME:
by = By.CSS_SELECTOR
value = '[name="%s"]' % value
return self.execute(Command.FIND_ELEMENT, {
'using': by,
'value': value})['value']
**********
可以看到对ID、TAG_NAME、CLASS_NAME、NAME四种样式,selenium都将其转化为了CSS_SELECTOR的格式。
当然,我们使用的时候也可以直接调用find_element指定by和value,这是单数的调用,复数同理
**********
网友评论