Java Selenium

接上一篇,我们依然以京东的网站做示例。

三,单选项

下面来做这样一条case: 

1. 登录京东旅行网页。

2. 在国内机票板块,购买从北京到武汉的往返机票,时间为明天出发,一周后返回。

3.搜索机票。

示例代码:

package JD_Practice;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumAction_RadioButton {
    private static WebDriver driver;
    private static String baseUrl;

    public static void main(String[] args) {
        driver=new FirefoxDriver();
        baseUrl="http://jipiao.jd.com/";
        driver.get(baseUrl);
        driver.manage().window().maximize();
        
        PlainTravel_RadioButton(driver);
        //driver.quit();
    }
    
    public static void PlainTravel_RadioButton(WebDriver dr){
        dr.findElement(By.id("depCity")).clear();
        dr.findElement(By.id("depCity")).sendKeys("±±¾©");
        
        dr.findElement(By.id("arrCity")).clear();
        dr.findElement(By.id("arrCity")).sendKeys("Î人");
        
        dr.findElement(By.id("roundFlight")).click();
        
        Calendar cal2= Calendar.getInstance();
        SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
        String CurrentDate = f.format(cal2.getTime());
        String StartDate = String.valueOf((Integer.valueOf(CurrentDate)+1));
        String RoundDate = String.valueOf((Integer.valueOf(CurrentDate)+7));
        
        System.out.println(CurrentDate);
        System.out.println(StartDate);
        System.out.println(RoundDate);
        
        JavascriptExecutor js = (JavascriptExecutor)driver;
        js.executeScript("document.getElementById('depDate').readOnly=false;");
        dr.findElement(By.id("depDate")).clear();
        dr.findElement(By.id("depDate")).sendKeys(StartDate);
        
        js.executeScript("document.getElementById('arrDate').readOnly=false;");
        dr.findElement(By.id("arrDate")).clear();
        dr.findElement(By.id("arrDate")).sendKeys(RoundDate);
        
        dr.findElement(By.id("validQuery")).click();    
    }
}

运行成功后跳转到机票页面

四,多选项
练习:勾选以下所有复选框

  @Test
  public void testUntitled() throws Exception {
    driver.get(baseUrl + "/Search?keyword=Apple&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&bs=1&wq=Apple&ev=exbrand_Apple%5E&click=6");
    driver.findElement(By.xpath("//div[@id='J_feature']/ul/li[1]")).click();
    driver.findElement(By.xpath("//div[@id='J_feature']/ul/li[2]")).click();
    driver.findElement(By.xpath("//div[@id='J_feature']/ul/li[3]")).click();
    driver.findElement(By.xpath("//div[@id='J_feature']/ul/li[4]")).click();
  }

 其实这个例子写的并不好,本想着用一个List ,一个Xpath就直接把这四个复选框,全部放到List里,然后挨个遍历并勾选。。。But这里面是有坑的。每次勾选一个过滤条件,页面就会刷新,接着你List的元素就会找不到 , 需要找到更好的办法去解决这个问题。

原文地址:https://www.cnblogs.com/AryaZ/p/7640624.html