Selnium-八大元素定位方法
selenium提供了定位元素的API,这些方法斗殴被定义在WebDriver类中,这些方法都以find开头.
# | 方法名称 | 描述 |
1 | find_element_by_id | 通过id定位元素 |
2 | find_element_by_xpath | 通过xpath定位元素 |
3 | find_element_by_link_text | 通过连接文本定位元素 |
4 | find_element_by_partial_link_text | 通过部分连接文本定位 |
5 | find_element_by_name | 通过元素属性名称定位 |
6 | find_element_by_tag_name | 通过标签名称定位,如h1,input等 |
7 | find_element_by_class_name | 通过css class定位 |
8 | find_element_by_css_selector | 通过css选择器 |
from selenium import webdriver from time import sleep class testcase(object): def __init__(self): self.driver = webdriver.Chrome() self.driver.get('http://www.baidu.com') self.driver.maximize_window() sleep(1) def test_id(self): self.driver.find_element_by_id('kw').send_keys('selenium') self.driver.find_element_by_id('su').click() sleep(1) self.driver.quit() def test_name(self): self.driver.find_element_by_name('wd').send_keys('selenium') self.driver.find_element_by_id('su').click() sleep(1) self.driver.quit() def test_link_text(self): self.test_id() self.driver.find_element_by_link_text('百度首页').click() sleep(1) def test_partial_link_text(self): self.test_id() self.driver.find_element_by_partial_link_text('首页').click() sleep(1) def test_xpath(self): self.driver.find_element_by_xpath('//*[@id="kw"]').send_keys('selenium') self.driver.find_element_by_id('su').click() sleep(1) def test_tag_name(self): tag = self.driver.find_element_by_tag_name('input')[0] def test_css_selector(self): self.driver.find_element_by_css_selector('#kw').send_keys('selenium') self.driver.find_element_by_id('su').click() sleep(1) def test_class_name(self): self.driver.find_element_by_class_name('s_ipt').send_keys('selenium') self.driver.find_element_by_id('su').click() sleep(1) if __name__=='__main__': testcase().test_id() testcase().test_name() testcase().test_link_text() testcase().test_partial_link_text() testcase().test_xpath() testcase().test_tag_name() testcase().test_css_selector() testcase().test_class_name()