通常selenium By 可以通過id,class,xpath,css等定位頁面元素。
id 和class比較簡單,此處略....
介紹下xpath的常用內置函數 contains()/not (contains()), starts-with()/ends-with(), position(), last()...
代碼如下
@FindBy(how = How.XPATH, using = "//span[starts-with(@id,'bn_id')]/span[contains(@class,'bn_class')]") private List<WebElement> bnSpan;
@FindBy(how = How.XPATH, using = "//div[contains(text(),'report')]") private WebElement reportXpath;
@FindBy(how = How.XPATH, using = "//span[not(contains(@class,'bn_classB'))]") private List<WebElement> bnXpath;
position()--指定該div的排位
@FindBy(how = How.XPATH, using = "//li[@id='li_id']/div[position()=1]") private List<WebElement> firstDiv;
last() --指定最后一個節點,
driver.findElement(By.xpath("(//div[@class='bt_class'])[last()]"))
ps. 用xpath定位元素,若驗證其正確與否,可在console使用方法$x(xpath). e.g. :$x("//div[@id='ur']")
再簡單說下css,個人總結其語法規則
空格后面是tag名
#后為id
. 后為class
例如 用css定位如下Yes 的button, 其值可寫成
.class_6 button.btn-yes