selenium元素总结

生成一个web对象

IWebDriver driver;
driver = new FirefoxDriver();

selenium打开浏览器

package org.coderinfo.demo;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class StartBrowser {
public static void main(String[] args) {
/*
* 如果你的 FireFox 没有安装在默认目录,那么必须在程序中设置 例如:
* System.setProperty("webdriver.firefox.bin"
* ,"D:\\Program Files\\Mozilla Firefox\\firefox.exe");
*/
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com.hk");
}

跳转到指定页面
driver.Navigate().GoToUrl(baseURL + "/");
driver.title 取得当前页的title
driver.url 取得当前页的url

输入框(text field or textarea)

找到输入框元素:IWebElement element = driver.findElement(By.id("passwd-id"));

在输入框中输入内容:

element.sendKeys(“test”);

将输入框清空:

element.clear();

获取输入框的文本内容:

element.Text;

单选项

 if (CreatePassengerPage.getInsurance().Selected == false)
  {
        CreatePassengerPage.getInsurance().Click();
  }

下拉选择框(Select)

 SelectElement selectCity=new SelectElement(driver.FindElement(By.Id("City")));

(1)通过下拉框的索引选中第二项                    selectCity.SelectByIndex(2);      

(2)通过下拉列表中的选项的value属性选中      selectCity.SelectByValue("10");

(3)通过下拉列表中的选项的Text属性选中      selectCity.SelectByText("北京");

下拉选择
   SelectElement feeBasisDDL = new SelectElement(newRule.getFeeBasisDDL());
   feeBasisDDL.SelectByText(CaseData["FeeBasis"].ToString());
定位frame中元素
(1)进入frame
  driver.SwitchTo().Frame("frame");
(2)定位元素
  driver.FindElement(By.Id("div1"));
  driver.FindElement(By.Id("input1"));
(3)退出frame
  driver.SwitchTo().DefaultContent();
如何处理alert、confirm、prompt对话框
(1)取得alert框信息
    Html代码:
    <input id = "alert" value = "alert" type = "button" nclick = "alert('欢迎!请按确认继续!');"/> 
        driver.FindElement(By.Id("alert")).Click();
        IAlert alert = driver.SwitchTo().Alert();
        Console.WriteLine(alert.Text);
        confirm.Dismiss(); //点弹框关闭
(2)取得输出对话框上面的文字
    Html代码:
    <input id = "confirm" value = "confirm" type = "button" nclick = "confirm('确定吗?');"/>
        driver.FindElement(By.Id("confirm")).Click();
        IAlert confirm = driver.SwitchTo().Alert();
        Console.WriteLine(confirm.Text);
        confirm.Accept(); //点击确定
(3)点击按钮,输入名字,然后点击确认
    Html代码:
    <input id = "prompt" value = "prompt" type = "button" nclick = "var name = prompt('请输入你的名字:','请输入 
    你的名字'); document.write(name) "/>
        driver.FindElement(By.Id("prompt")).Click();
        IAlert prompt = driver.SwitchTo().Alert();
        Console.WriteLine(prompt.Text);
        prompt.SendKeys("Hello");
        prompt.Accept(); //点击确定
执行js脚本
((IJavaScriptExecutor) driver).ExecuteScript("js")

<input id="FHX_txtFromDate" type="text" readonly="readonly" name="FromTime" autocomplete="off" placeholder="yyyy-mm-dd" style="background-image: url("http://pic.c-ctrip.com/cquery/pic_aftertomorrow.png"); background-position: right center; background-repeat: no-repeat;"/>

l在实际编写脚本的过程中经常会遇到很多元素的属性是readonly的,表示此元素只读,不可进行赋值操作(此类情况常出现于日历框组件中)
l对于此类元素如果希望变更他的值,对于直接操作日历框会比较复杂,日历框的元素表达是按天拼接的,如果直接操作会需要做较多的运算和处理
l对于此类元素,只能通过JS修改元素的属性,去掉只读属性后就可以直接赋值了
修改元素属性方法

/// <summary>

        /// 设置元素只读属性为否

        /// </summary>

        /// <param name="type">ById、ByName、ByTagName</param>

        /// <param name="value">value</param>

        public void setReadOnlyFalseByAttribute(string type, string value)

        {

            string js = "";

            switch (type)

            {

                case "ById":

                    js = "document.getElementById('" + value + "').readOnly=false;";

                    break;

                case "ByName":

                    js = "document.getElementsByName('" + value + "').item(O).readOnly=false;";

                    break;

                case "ByTagName":

                    js = "document.getElementsByTagName('" + value + "').item(O).readOnly=false;";

                    break;

            }

            ((IJavaScriptExecutor)driver).ExecuteScript(js);

        }

findElenments中找某一个元素
       int num = driver.FindElements(By.XPath("//div[text()='更多支付方式']")).Count;
       if (Convert.ToBoolean(num))
           {
                CreatePayPage.getMorePay().Click();
           }
IWebDriver driver = new FirefoxDriver();
INavigation navigation = driver.Navigate();
navigation.GoToUrl(http://www.baidu.com);
navigation.GoToUrl("http://tieba.baidu.com/f/search/adv");
IWebElement select = driver.FindElement(By.Name("sm"));
string targetText = "按相关性排序";
System.Collections.Generic.IList<IWebElement> ptions = select.FindElements(By.TagName("option"));
for (int i = 0; i < options.Count; i++)
{
if (options[i].Text == targetText)
{
options[i].Click();
}
}
WebDriver driver = new FirefoxDriver();
Navigation navigation = driver.navigate();
navigation.to(http://www.baidu.com);
navigation.to("http://tieba.baidu.com/f/search/adv");
WebElement select = driver.findElement(By.name("sm"));
String targetText = "按相关性排序";
java.util.List<WebElement> ptions = select.findElements(By.tagName("option"));
for (int i = 0; i < options.size(); i++)
{
if (options.get(i).getText().equals(targetText))
{
options.get(i).click();
}
}

  try
            {
              if (driver.WindowHandles.Count > 0)
              {
                   //选择乘客,下一步核对
                    PassengerBusiness Passenger = new PassengerBusiness(driver, CaseData, CheckData);
                    Passenger.PassengerMessage(path, casename);
                    //支付并验证
                    PayEntryBusiness PayEntry = new PayEntryBusiness(driver, CaseData, CheckData);
                    PayEntry.Pay(path, casename);
                }
            }
            catch (Exception e)
            {
                Log.Info("搜索时异常,直接pass用例");
            }
判断页面是否有元素
  public IWebElement getDivContactModule()
        {
            return driver.FindElements(By.Id("contactInfo")).Count > 0 ? driver.FindElement(By.Id("contactInfo")) : null;
        }

passengerInfo.getLblTotalAmount().Text.ToString().Trim().TrimStart('¥');
获取时间
now_time = DataTime.Now
获取明天
tomorrow = DataTime.Now.AddDay(1)
昨天
yestaday = DataTime.Now.AddDay(-1)
 Xml requestXML = new Xml(requestStr);
 requestXML.SetElementValueByXpath("//FlightInfos/FlightInfo[1]/EffectDate", string.Format("{0}T00:00:00", DateTime.Today.AddDays(5).ToString("yyyy-MM-dd")));
操作键盘TAB键
在selenium中隐藏元素由于属性是隐藏的,如果直接对隐藏属性进行操作会抛出异常
所以如果需要对隐藏元素,必须首先使隐藏元素弹出,此时元素的隐藏属性会失去
需要注意的时,实际在selenium中弹出隐藏元素,并非模拟操作那样鼠标点击就可以,必须要通过其他方式,如:使用TAB键从上一元素顺序切换到“出发城市”元素框上;或者通过对“出发城市”这个元素使用sendkey”\n”也可以弹出隐藏元素

 //操作键盘TAB键

Actions enter = new Actions(driver);

enter.SendKeys(Keys.Tab).Perform();

如何等待页面元素加载完成
(1)明确等待

driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromMinutes(5));
(2)隐形等待

如何得到弹出窗口
(1)当前窗口的句柄
    driver.CurrentWindowHandle
(2)所有窗口的句柄
    driver.WindowHandles
(3)根据句柄得到窗口
    if driver.CurrentWindowHandle=driver.WindowHandles[i]
    IWebDriver window=driver.SwitchTo().Window(driver.WindowHandles[i])
(4)根据窗口得到title,url
    window.Title
    window.Url
如何操作cookie
(1)增加一个name = "name",value="value"的cookie
    Cookie cookie=new Cookie("name","value");
        driver.Manage().Cookies.AddCookie(cookie);
(2)得到页面下所有的cookies,输入它的所在域、name、value、有效日期、路径
    ICookieJar cookies=driver.Manage().Cookies;
        Cookie co = cookies.GetCookieNamed("name");
        Console.WriteLine(co.Domain);
        Console.WriteLine(co.Name);
        Console.WriteLine(co.Value);
        Console.WriteLine(co.Expiry);
        Console.WriteLine(co.Path);
(3)删除cookie三种方法
    a)通过cookie的name
    driver.Manage().Cookies.DeleteCookieNamed("CookieName");
    b)通过cookie对象
    driver.Manage().Cookies.DeleteCookie(cookie);
    c)全部删除
    driver.Manage().Cookies.DeleteAllCookies();
如何利用Selenium-webdriver截图
        Screenshot screenShotFile = ((ITakesScreenshot)driver).GetScreenshot();
        screenShotFile.SaveAsFile("test",ImageFormat.Jpeg);
如何取得table中的内容
 (1)通过行得到列的方法
    private IWebElement GetCell(IWebElement row,int cell)
        {
            IList<IWebElement> cells;
            IWebElement target = null;
            //列里面有"<th>"、"<td>"两种标签,所以分开处理
            if(row.FindElements(By.TagName("th")).Count>0)
            {
                cells = row.FindElements(By.TagName("th"));
                target = cells[cell];
            }

            if(row.FindElements(By.TagName("td")).Count>0)
            {
                cells = row.FindElements(By.TagName("td"));
                target = cells[cell];
            }
            return target;
        }
(2)通过By得到行的方法
    public String GetCellText(By by,String tableCellAddress)
        {
            //得到table元素
            IWebElement table = driver.FindElement(by);
            //对所要查找的单元格位置字符进行分解,得到对应的行、列
            int index = tableCellAddress.Trim().IndexOf('.');
            int row = Convert.ToInt32(tableCellAddress.Substring(0, index));
            int cell = Convert.ToInt32(tableCellAddress.Substring(index + 1));
            //得到table表中所有行对象,并得到所要查询的行对象
            IList<IWebElement> rows = table.FindElements(By.TagName("tr"));
            IWebElement theRow = rows[row];
            return GetCell(theRow, cell).Text;
        }
(3)通过参数得到对应行列的内容
    Console.WriteLine(GetCellText(By.Id("mytable"),"0.2")); //得到id="mytable"中的第一行第三列的表格内容

多选项(checkbox)

多选项的操作和单选的差不多:

WebElement checkbox = driver.findElement(By.id("myCheckbox."));

checkbox.click();

checkbox.clear();

checkbox.isSelected();

checkbox.isEnabled();

按钮(button)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值