selenium循序渐进--元素定位
上一篇 /
下一篇 2014-06-23 16:23:21
/ 个人分类:selenium
元素定位的方法:findElement() 与 findElements()
findElement() 该方法返回基于指定查询条件的webElement对象,或抛出不符合条件的异常 eg:driver.findElement(By.id("userID"));
findElements() 该方法返回指定查询条件的WebElement的对象集合,或返回null
多学一招:WebElement类支持查询子类元素,如果页面中存在重复元素,但在不同div中,我们可以先定位到其父元素,然后定位其子元素,方法如下:
WebElement hello = driver.findElement(By.id("div1")).findElement(By.lindText("hello"));
By ID
<div id="coolestWidgetEvah">...</div>
IWebElement element = driver.FindElement(By.Id("coolestWidgetEvah"));
By Class Name
<div class="cheese"><span>Cheddar</span></div><div class="cheese"><span>Gouda</span></div>
IList<IWebElement> cheeses = driver.FindElements(By.ClassName("cheese"));
By Tag Name
driver.SwitchTo().Frame("__SSO_iframe_1");<iframe. src="..."></iframe>
IWebElement frame. = driver.FindElement(By.TagName("iframe"));
By Link Text
<a href="http://www.google.com/search?q=cheese">cheese</a>
IWebElement cheese = driver.FindElement(By.LinkText("cheese"));
By CSS
<div id="food"><span class="dairy">milk</span><span class="dairy aged">cheese</span
IWebElement cheese = driver.FindElement(By.CssSelector("#food span.dairy.aged"));!!
Using JavaScript
IWebElement element = (IWebElement) ((IJavaScriptExecutor)driver).ExecuteScript("return $('.cheese')[0]");
By XPATH
<input type="text" name="example" />
<INPUT type="text" name="other" />
IList<IWebElement> inputs = driver.FindElements(By.XPath("//input"));
使用xpath定位元素,相比cssSelector,xpath是我比较常用的一种定位元素的方式,因为它很方便,缺点是,消耗系统性能
1、使用绝对路径定位元素
driver.findElement(By.xpath("/html/body/div/form/input"))
2、使用相对路径定位元素
driver.findElement(By.xpath("//input")) 返回查找到的第一个符合条件的元素
3、使用索引定位元素,索引的初始值为1,注意与数组等区分开
driver.findElement(By.xpath("//input[2]")) 返回查找到的第二个符合条件的元素
4、结合属性值来定位元素
driver.findElement(By.xpath("//input[@id='username']"));
driver.findElement(By.xpath("//img[@alt='flowr']"));
5、使用逻辑运算符,结合属性值定位元素,and与or
driver.findElement(By.xpath("//input[@id='username' and @name='userID']"));
6、使用属性名来定位元素
driver.findElement(By.xpath("//input[@button]"))
7、类似于cssSlector,使用部分属性值匹配元素
starts-with() driver.findElement(By.xpath("//input[stars-with(@id,'user')]"))
ends-with driver.findElement(By.xpath("//input[ends-with(@id,'name')]"))
contains() driver.findElement(By.xpath("//input[contains(@id,"ernam")]"))
8、使用任意属性值匹配元素
driver.findElement(By.xpath("//input[@*='username']"))
9、使用xpath轴来定位元素
//td[@id='invoice_title-inputCell']/following-sibling::td/div
//span[text()='发票抬头选择界面']/ancestor::div[6]//input[@name='typeValue']
10、使用xpath的text函数
driver.findElement(By.xpath("//span[contains(text(),'hello')]")) 包含匹配
driver.findElement(By.xpath("//span[text()='新闻']")) 绝对匹配
收藏
举报
TAG: