分析:https://github.com/頁面Licss
<div class="header header-logged-out"> <div class="container clearfix"> <a class="header-logo-wordmark" href="https://github.com/">Github</a> <ul class="top-nav"> <li class="explore"><a href="https://github.com/explore">Explore GitHub</a></li> <li class="search"><a href="https://github.com/search">Search</a></li> <li class="features"><a href="https://github.com/features">Features</a></li> <li class="blog"><a href="https://github.com/blog">Blog</a></li> </ul> <div class="header-actions"> <a class="button primary" href="https://github.com/signup">Sign up for free</a> <a class="button" href="https://github.com/login">Sign in</a> </div> </div>
WebElement element1 = webdriver.findElement(By.id("header"));
WebElement element2 = webdriver.findElement(By.name("name"));
WebElement element3 = webdriver.findElement(By.tagName("a"));
WebElement element4 = webdriver.findElement(By.xpath("//a[@title='logo']"));
WebElement element5 = webdriver.findElement(By.cssSelector(".feautures"));
WebElement element6 = webdriver.findElement(By.linkText("Blog"));
WebElement element7 = webdriver.findElement(By.partialLinkText("Ruby"));
WebElement element8 = webdriver.findElement(By.className("login")); |
List<WebElement> webElements = webdriver.findElements(By
.xpath("//ul[@class='nav logged_out']/li")); |
13使用 CSS 選擇器 (By.cssSelector()
) 來檢索LI
標記。git
List<WebElement> webElements = webdriver.findElements(By
.cssSelector("ul.nav li")); |
可在所檢索的項數量上生成斷言,如 清單 14所示。github
Assert.assertEquals(5, webElements.size()); |
LI
標記數量等於 5。
下一步是檢索每一個LI
標記中的每一個錨點(A
標記)。web
展現瞭如何在第一個LI
中獲取錨點。此用例使用了 tagName (By.tagName()
) 策略。測試
WebElement anchor1 = webElements.get(0).findElement(By.tagName("a")); |
您可使用相似的方法收集到全部的 5 個錨點,如 清單 16所示。spa
WebElement anchor1 = webElements.get(0).findElement(By.tagName("a"));
WebElement anchor2 = webElements.get(1).findElement(By.tagName("a"));
WebElement anchor3 = webElements.get(2).findElement(By.tagName("a"));
WebElement anchor4 = webElements.get(3).findElement(By.tagName("a"));
WebElement anchor5 = webElements.get(4).findElement(By.tagName("a")); |
在這一階段,您能夠驗證,錨點內的文本是否與所指望的字符串一致。要檢索標記內的文本,WebDriver 提供了getText()
方法。清單 展現了完整的測試方法,以及測試底部的斷言。.net
Assert.assertEquals("Signup and Pricing", anchor1.getText()); Acode
ssert.assertEquals("Explore GitHub", anchor2.getText());blog
Assert.assertEquals("Features", anchor3.getText());ci
Assert.assertEquals("Blog", anchor4.getText());
Assert.assertEquals("Login", anchor5.getText());