读了虫师《Selenium 2自动化测试实战 基于Python语言》一书,感触颇深,内容十分丰盛。现整顿下来,供后续学习参考应用。本次次要整顿的是元素定位的形式。
1. id定位
find_element_by_id();
2. name定位
find_element_by_name();
3. class属性定位
find_element_by_class_name();
4. tag属性定位
find_element_by_tag_name();
5. 元素标签之前的文本信息来定位
find_element_by_link_text();
6. 取文本链接的一部分来定位
find_element_by_partial_link_text();
7. xpath多种定位策略
find_element_by_xpath();
①绝对路径:
find_element_by_xpath("html/body/div[2]/div[2]/div[3]/div[2]/form/input[1]");
②元素属性:
find_element_by_xpath("//input[@id='qwe']"); find_element_by_xpath("//input[@name='qwe']"); find_element_by_xpath("//input[@class='qwe']");find_element_by_xpath("//*[@id='qwe']");
③层级属性:
find_element_by_xpath("//span[@class='qwe']/input");find_element_by_xpath("//form[@id='qwe']/span[2]/input");
④运算逻辑:
find_element_by_xpath("//input[@id='qwe' and @class='qwer']/span/input");
8. css选择器定位
find_element_by_css_selector();
其中css也有多种策略:
①class属性:
find_element_by_css_selector(".qwe");
②id属性:
find_element_by_css_selector("#qwe");
③标签名:
find_element_by_css_selector("input");
A.父子关系:
find_element_by_css_selector("span>input");
B.属性定位:
find_element_by_css_selector('[type="submit"]');
C.组合定位:
find_element_by_css_selector("form.fm>span>input>input.qwe");
9.BY元素定位
以上提到的8种定位办法,webdriver还提供了另一套写法,即对立调用find_element()办法,通过BY来申明定位的办法,并且传入对应定位办法的定位参数。应用BY之前须要插入BY类:
from selenium.webdriver.common.by import Byfind_element(BY.ID,"qwe");find_element(BY.NAME,"qwe");find_element(BY.CLASS_NAME,"qwe");find_element(BY.TAG_NAME,"qwe");find_element(BY.LINK_TEXT,"xxxxx");find_element(BY.PARTIAL_LINK_TEXT,"dddd");find_element(BY.XPATH,"//* [@id='qwe']");find_element(BY.CSS_CELECTOR," span>input ");