Java+Selenium3方法篇24-单选和多选按钮操作

本篇介绍 webdriver处理前端单选按钮的操作。单选按钮一般叫raido button,就像我们在电子版的单选答题过程一样,单选只能点击一次,如果点击其他的单选,之前单选被选中状态就会变成未选中。单选按钮的点击,一样是 使用click方法。下面我们介绍百度新闻首页中有两个单选按钮,我们根据for选好,依次点击第一个,然后点击第二个,由于第一个是默认选中状态,所以 看不到第一个点击的效果。

相关脚本代码如下。

  1. package lessons;
  2. import java.util.ArrayList;
  3. import java.util.concurrent.TimeUnit;
  4. import org.openqa.selenium.By;
  5. import org.openqa.selenium.WebDriver;
  6. import org.openqa.selenium.WebElement;
  7. import org.openqa.selenium.chrome.ChromeDriver;
  8. public class ElementOpration {
  9. public static void main(String[] args) throws Exception {
  10. System.setProperty("webdriver.chrome.driver", ".\\Tools\\chromedriver.exe");
  11. WebDriver driver = new ChromeDriver();
  12. driver.manage().window().maximize();
  13. driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  14. driver.get("http://news.baidu.com");
  15. Thread.sleep(1000);
  16. // 把单选按钮放在一个list里面
  17. ArrayList<WebElement> search_type = (ArrayList<WebElement>) driver.findElements(By.xpath("//*/p[@class='search-radios']/input"));
  18. for(WebElement ele : search_type){
  19. ele.click();
  20. Thread.sleep(1000);
  21. }
  22. }
  23. }

上面介绍了单选按钮是采用click方法,其实多选按钮一样是采用click,我们这里打开一个问卷调查,利用for循环去一次点击每个题目的单选和多选按钮。自己运行下观察效果。

  1. package lessons;
  2. import java.util.ArrayList;
  3. import java.util.concurrent.TimeUnit;
  4. import org.openqa.selenium.By;
  5. import org.openqa.selenium.WebDriver;
  6. import org.openqa.selenium.WebElement;
  7. import org.openqa.selenium.chrome.ChromeDriver;
  8. public class ElementOpration {
  9. public static void main(String[] args) throws Exception {
  10. System.setProperty("webdriver.chrome.driver", ".\\Tools\\chromedriver.exe");
  11. WebDriver driver = new ChromeDriver();
  12. driver.manage().window().maximize();
  13. driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  14. driver.get("https://www.sojump.com/m/2792226.aspx/");
  15. Thread.sleep(1000);
  16. // 把单选按钮放在一个list里面
  17. ArrayList<WebElement> answer_options = (ArrayList<WebElement>) driver.findElements(By.xpath("//*/div[@id='divQuestion']/fieldset/div/div/div/span/input/../a"));
  18. for(WebElement ele : answer_options){
  19. ele.click();
  20. Thread.sleep(1000);
  21. }
  22. }
  23. }

上面介绍了一组元素采用for循环遍历操作的方法,如果是单个单选按钮或者单个多选按钮,需要用到根据单选按钮旁边的文字去定位该单选按钮,所以这里需要 用到Xpath的相对路径写法。其实上面第二个例子input/../a就是采取了相对路径写法,才能看到点击选中的效果。

05-24 08:38