您的位置:首页 > 编程语言 > C#

Selenium API(C#)

2013-11-23 12:20 155 查看
1FetchingaPage

driver.Url="http://www.google.com";

2LocatingUIElements(WebElements)


ByID

Thisisthemostefficientandpreferredwaytolocateanelement.CommonpitfallsthatUIdevelopersmakeishavingnon-uniqueid’sonapageorauto-generatingtheid,bothshouldbeavoided.Aclassonanhtmlelementismoreappropriatethananauto-generatedid.

Exampleofhowtofindanelementthatlookslikethis:

<divid="coolestWidgetEvah">...</div>


IWebElementelement=driver.FindElement(By.Id("coolestWidgetEvah"));

ByClassName

“Class”inthiscasereferstotheattributeontheDOMelement.OfteninpracticalusetherearemanyDOMelementswiththesameclassname,thusfindingmultipleelementsbecomesthemorepracticaloptionoverfindingthefirstelement.

Exampleofhowtofindanelementthatlookslikethis:

<divclass="cheese"><span>Cheddar</span></div><divclass="cheese"><span>Gouda</span></div>

IList<IWebElement>cheeses=driver.FindElements(By.ClassName("cheese"));

ByTagName

TheDOMTagNameoftheelement.

Exampleofhowtofindanelementthatlookslikethis:

<iframesrc="..."></iframe>

IWebElementframe=driver.FindElement(By.TagName("iframe"));

ByLinkText

Findthelinkelementwithmatchingvisibletext.

Exampleofhowtofindanelementthatlookslikethis:

<ahref="http://www.google.com/search?q=cheese">cheese</a>
IWebElementcheese=driver.FindElement(By.LinkText("cheese"));

ByCSS

Likethenameimpliesitisalocatorstrategybycss.Nativebrowsersupportisusedbydefault,sopleaserefertow3ccssselectors<http://www.w3.org/TR/CSS/#selectors>foralistofgenerallyavailablecssselectors.Ifabrowserdoesnothavenativesupportforcssqueries,thenSizzleisused.IE6,7andFF3.0currentlyuseSizzleasthecssqueryengine.

Bewarethatnotallbrowserswerecreatedequal,somecssthatmightworkinoneversionmaynotworkinanother.

Exampleoftofindthecheesebelow:

<divid="food"><spanclass="dairy">milk</span><spanclass="dairyaged">cheese</span
IWebElementcheese=driver.FindElement(By.CssSelector("#foodspan.dairy.aged"));

ByXPATH

Atahighlevel,WebDriverusesabrowser’snativeXPathcapabilitieswhereverpossible.Onthosebrowsersthatdon’thavenativeXPathsupport,wehaveprovidedourownimplementation.Thiscanleadtosomeunexpectedbehaviourunlessyouareawareofthedifferencesinthevariousxpathengines.

DriverTagandAttributeNameAttributeValuesNativeXPathSupport
HtmlUnitDriverLower-casedAstheyappearintheHTMLYes
InternetExplorerDriverLower-casedAstheyappearintheHTMLNo
FirefoxDriverCaseinsensitiveAstheyappearintheHTMLYes
Thisisalittleabstract,soforthefollowingpieceofHTML:

<inputtype="text"name="example"/>
<INPUTtype="text"name="other"/>


IList<IWebElement>inputs=driver.FindElements(By.XPath("//input"));

UsingJavaScript

YoucanexecutearbitraryjavascripttofindanelementandaslongasyoureturnaDOMElement,itwillbeautomaticallyconvertedtoaWebElementobject.

SimpleexampleonapagethathasjQueryloaded:



IWebElementelement=(IWebElement)((IJavaScriptExecutor)driver).ExecuteScript("return$('.cheese')[0]");


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: