老早就想寫一些Selenium測試架構的搭建,但是時間和想法都不太成熟。今天 就大概粗略的和大家分享一下。
本文的背景假設讀者有一定的selenium使用經驗。
1.元素定位
大家都知道,網頁這個東西在瀏覽器裡展現出來的是一個完整的xml,所以可 以通過xml的訪問方式,字串查詢,正則等來訪問xml。
selenium支援的遍曆模式有:
public class By { protected By(); protected By(Func<ISearchContext, IWebElement> findElementMethod, Func<ISearchContext, ReadOnlyCollection<IWebElement>> findElementsMethod); public static bool operator !=(By one, By two); public static bool operator ==(By one, By two); protected string Description { get; set; } protected Func<ISearchContext, IWebElement> FindElementMethod { get; set; } protected Func<ISearchContext, ReadOnlyCollection<IWebElement>> FindElementsMethod { get; set; } public static By ClassName(string classNameToFind); public static By CssSelector(string cssSelectorToFind); public override bool Equals(object obj); public virtual IWebElement FindElement(ISearchContext context); public virtual ReadOnlyCollection<IWebElement> FindElements(ISearchContext context); public override int GetHashCode(); public static By Id(string idToFind); public static By LinkText(string linkTextToFind); public static By Name(string nameToFind); public static By PartialLinkText(string partialLinkTextToFind); public static By TagName(string tagNameToFind); public override string ToString(); public static By XPath(string xpathToFind); }
大家可以看到最後一個是通過xpath,其他的例如classname,cssselector等 估計也是通過xpath來實現的。大家可以去具體看看webdrvier實現的源碼,驗證 一下思想,如果後續有時間,我會剖析一下webdriver的原始碼。
好了,有了xpath,就可以定位網頁上的元素了。