- 模块的引入
- from selenium import webdriver # 引入webdriver
- id定位
- find_element_by_id('kw') # id为kw的元素
- name定位
- find_element_by_name('user') # name 为user的元素
- class定位
- find_element_by_class_name("s_ipt") # class为s_ipt的元素
- tag定位
- find_element_by_tag_name("input") # tag为input的元素
- link定位
- find_element_by_link_text("新闻") # a标签文本内容为“新闻”
- find_element_by_link_text("新闻") # a标签文本内容为“新闻”
- partial link 定位
- find_element_by_partial_link_text("一个很长的") # a标签文本内容中含有“一个很长的”(模糊查询)
- XPath定位
- XPath 是一种在 XML 文档中定位元素的语言。因为 HTML 可以看做 XML 的一种实现,所以 selenium
用户可是使用这种强大语言在 web 应用中定位元素。 - 绝对路径
- find_element_by_xpath("/html/body/div/div[2]/div/div/div/from/span/input") # div[2]表示第二个 div 标签
- find_element_by_xpath("/html/body/div/div[2]/div/div/div/from/span/input") # div[2]表示第二个 div 标签
- 属性定位
- find_element_by_xpath("//input[@id='kw']") # id为kw的input标签
- 层级与属性结合
- find_element_by_xpath("//span[@class='bg s_btn_wr']/input") # class为bg s_btn_wr的span标签下的input标签
- find_element_by_xpath("//span[@class='bg s_btn_wr']/input") # class为bg s_btn_wr的span标签下的input标签
- 逻辑运算符
- find_element_by_xpath("//input[@id='kw' and @class='su']/span/input") # id为kw 且 class为su的input标签下的span标签下的input标签
- find_element_by_xpath("//input[@id='kw' and @class='su']/span/input") # id为kw 且 class为su的input标签下的span标签下的input标签
- XPath 是一种在 XML 文档中定位元素的语言。因为 HTML 可以看做 XML 的一种实现,所以 selenium
- CSS定位
- find_element_by_css_selector(".s_ipt") # class
- find_element_by_css_selector("#kw") # id
- find_element_by_css_selector("input") # tag
- find_element_by_css_selector("span>input") # 子代选择
- find_element_by_css_selector("span input") # 后代选择
- find_element_by_css_selector("input[autocomplete='off']") # 属性
- find_element_by_css_selector("span.bg s_ipt_wr") # 组合
- find_element_by_css_selector(".s_ipt") # class
- By 定位
- find_element()方法只用于定位元素。它需要两个参数,第一个参数是定位方式,这个由 By 提供;另
第二个参数是定位的值。在使用 By 时需要将 By 类导入。 - 引入
- from selenium.webdriver.common.by import By
- from selenium.webdriver.common.by import By
- find_element(By.ID,"kw")
- find_element(By.NAME,"wd")
- find_element(By.CLASS_NAME,"s_ipt")
- find_element(By.TAG_NAME,"input")
- find_element(By.LINK_TEXT,u"新闻")
- find_element(By.PARTIAL_LINK_TEXT,u"新")
- find_element(By.XPATH,"//*[@class='bg s_btn']")
- find_element(By.CSS_SELECTOR,"span.bg s_btn_wr>input#su")
- find_element()方法只用于定位元素。它需要两个参数,第一个参数是定位方式,这个由 By 提供;另