基于Java和Python常用的SeleniumAPI

常用API Java Python
打开浏览器 new XXXXDriver() webdriver.XXX()
隐式等待 待确认 implicitly_wait()
获取网址 get() get()
关闭当前页面 close() close()
关闭所有页面 quit() quit()
浏览器后退 back() back()
浏览器前进 forward() forward()
浏览器最大化 maximize() maximize_window()
设置浏览器大小 setSize(new Dimension(width,heigth)) set_window_size(width,heigth)
控件元素定位 findElement(By.XX()) find_element_by_xx()
获取当前页面Title getTitle() title
获取当前页面源码 getPageSource() page_source
点击 click() click()
文本框输入 sendkeys() send_keys()
清空文本框 clear() clear()
获取控件元素文本 getText() text
获取控件元素属性值 getAttribute() get_attribute()
鼠标右击 contextClick() context_click()
鼠标双击 doubleClick() double_click()
拖动 dragAndDrop() drag_and_drop()
鼠标移动到某个元素上 moveToElement() move_to_element()
切换Frame switchTo.frame() switch_to.frame()
切换回默认Frame switchTo().defaultContent() switch_to.default_content()
切换窗口 switchTo.window() switch_to.window()
切换至警告框 switchTo.alert() switch_to.alert
警告框确认 accept() accept()
警告框取消 dismiss() dismiss()
获取当前句柄 getWindowHandle() current_window_handle
获取所有句柄 getWindowHandles() window_handles()
判断元素是否可见 isDisplayed() is_displayed()
下拉框选取 selectByIndex()、selectByValue()、selectByVisibleText() select_by_index()、select_by_value()、select_by_visible_text()
执行JS executeScript() execute_script()
截图操作 getScreenshotAs() get_screenshot_as_file()

相关例子

切换警告框
  • Python
    def test_alert(self):
        driver = webdriver.Chrome()
        driver.get("file:///XXXXX/index.html")
        time.sleep(1)
        # Alert框:只有一个确定按钮
        driver.find_element_by_class_name("alert").click()
        time.sleep(1)
        alert = driver.switch_to.alert
        time.sleep(1)
        alert.accept()
        # Confirm框:含确定和取消按钮
        driver.find_element_by_class_name("confirm").click()
        time.sleep(1)
        confirm = driver.switch_to.alert
        time.sleep(1)
        confirm.dismiss()
        time.sleep(1)
        confirm.accept()
        time.sleep(1)
        # Prompt框:可以输入文本的警告框
        driver.find_element_by_class_name("prompt").click()
        time.sleep(1)
        prompt = driver.switch_to.alert
        time.sleep(1)
        prompt.send_keys("Just test")
        time.sleep(1)
        prompt.accept()
        prompt.accept()
  • Java
    //切换至警告弹窗
    public void testAlert() throws InterruptedException {
        WebDriver driver = new ChromeDriver();
        driver.get("file:///XXXXX/index.html");
        sleep(1000);
        //  Alert框:只有一个确定按钮
        driver.findElement(By.xpath("//*[@id=\"alert\"]/input")).click();
        sleep(1000);
        Alert alart = driver.switchTo().alert();
        alart.accept();
        sleep(1000);
        //Confirm框:含有确定和取消按钮
        driver.findElement(By.xpath("//*[@id=\"confirm\"]/input")).click();
        sleep(1000);
        Alert alert2 = driver.switchTo().alert();
        alert2.dismiss();
        sleep(1000);
        alart.accept();
        sleep(1000);
        driver.findElement(By.className("prompt")).click();
        sleep(1000);
        Alert prompt = driver.switchTo().alert();
        sleep(1000);
        prompt.sendKeys("Just test");
        sleep(1000);
        prompt.accept();
        prompt.accept();
切换Frame
  • Python
    def test_frame(self):
        driver = webdriver.Chrome()
        driver.get("file:///XXXXX/index.html")
        time.sleep(1)
        # 通过定位到Frame控件方式进行切换
        # ele = driver.find_element_by_name("aa")
        ele = driver.find_element_by_class_name("frame")
        time.sleep(1)
        driver.switch_to.frame(ele)
        # 直接通过Frame的ID进行切换
        # driver.switch_to.frame("frame")
        text=driver.find_element_by_class_name("widgetStyle").text
        print(text)
        # 切换回外层Frame
        driver.switch_to.default_content()
        time.sleep(1)
        print(driver.find_element_by_class_name("widgetStyle").text)
  • Java
//    切换frame
    public void testFrame() throws InterruptedException {
        driver.get("file:///XXXXX/index.html");
        sleep(1000);
        //通过定位到Frame控件方式进行切换
        WebElement frame = driver.findElement(By.name("aa"));
        driver.switchTo().frame(frame);
        //直接通过Frame的ID进行切换
//        driver.switchTo().frame("frame");
        String text = driver.findElement(By.className("widgetStyle")).getText();
        System.out.println(text);
        //切换回外层Frame
        driver.switchTo().defaultContent();
        sleep(1000);
        System.out.println(driver.findElement(By.className("widgetStyle")).getText());
    }

多窗口切换
  • Python
    def test_window(self):
        driver = webdriver.Chrome()
        driver.get("file:///XXXXX/index.html")
        time.sleep(1)
        # 获取当前窗口的handle
        current_handle = driver.current_window_handle
        driver.find_element_by_class_name("open").click()
        # 遍历当前浏览器打开的窗口的handle
        for handle in driver.window_handles:
            # 判断是否在当前窗口,是跳过,否则切换
            if handle == current_handle:
                print(handle)
                continue
            driver.switch_to.window(handle)
            print(handle)
        time.sleep(3)
        print(driver.title)
  • Java
//    切换到新窗口
    public void testWindow() throws InterruptedException {
        driver.get("file:///XXXXX/index.html");
        sleep(3);
        driver.findElement(By.className("open")).click();
        sleep(3000);
        String handle = driver.getWindowHandle();
        for (String handles : driver.getWindowHandles()) {
            if (handles.equals(handle)) {
                System.out.println(handles);
                continue;
            } else {
                driver.switchTo().window(handles);
                System.out.println(handles);
            }
        }
        sleep(3000);
        System.out.println(driver.getTitle());
    }
显示等待
  • Python
    # 封装显示等待,Usage:find_element_until_visibility(driver,(By.XXX,"XXX"))
    def find_element_until_visibility(self,driver,locator,timeout=30):
        try:
            element = WebDriverWait(driver,timeout).until(expected_conditions.presence_of_element_located(locator))
            return element
        except NoSuchElementException as e:
            print("Element not Found:")
  • Java
    public static WebElement findElement(By by,int time){
        WebElement element = null;
        try{
            WebDriverWait wait = new WebDriverWait(driver,time);
            wait.until(ExpectedConditions.presenceOfElementLocated(by));
            element = driver.findElement(by);
        }catch (Exception e){
            System.out.println("元素:"+ by +" 没找到");
            e.printStackTrace();
        }
        return element;
    }
执行JS脚本
  • Python
    def test_js(self):
        driver = webdriver.Chrome()
        driver.get("file:///XXXXX/index.html")
        time.sleep(1)
        # 设置窗口大小为500*800
        driver.set_window_size(500,800)
        time.sleep(1)
        # 通过JS脚本,将窗口移动至2000*3000
        driver.execute_script("window.scrollTo(2000,3000)")
        time.sleep(2)
        # 通过JS脚本,将窗口移动至1000*0
        driver.execute_script("window.scrollTo(1000,0)")
        time.sleep(2)
        # 通过JS脚本,将窗口移动至0*3000
        driver.execute_script("window.scrollTo(0,3000)")
  • Java
//    执行JavaScript
    public void testJavaScript() throws InterruptedException {
        driver.get("file:///XXXXX/index.html");
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("document.getElementById(\"user\").setAttribute(\"type\",\"password\")");
        sleep(3000);
        js.executeScript("document.getElementById(\"user\").value = \"Parson\"");
        sleep(3000);
        js.executeScript("document.getElementById(\"user\").setAttribute(\"type\",\"text\")");
        js.executeScript("document.getElementById(\"user\").value = \"Password\"");
        driver.findElement(By.className("wait")).click();
        WebDriverWait wait = new WebDriverWait(driver, 30);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.className("red")));
        String text = driver.findElement(By.className("red")).getText();
        Assert.assertEquals(text,"wait for display");
    }
下拉框操作
  • Python
    def test_select(self):
        driver = webdriver.Chrome()
        driver.get("file:///XXXXX/index.html")
        time.sleep(1)
        ele = driver.find_element_by_id("moreSelect")
        selector = Select(ele)
        selector.select_by_index(2)
        time.sleep(3)
        selector.select_by_value("Honor")
  • Java
    public void testselect() throws InterruptedException {
        driver.get("file:///XXXXX/index.html");
        Thread.sleep(3000);
        WebElement ele = driver.findElement(By.id("moreSelect"));
        Select selector = new Select(ele);
        selector.selectByIndex(2);
        Thread.sleep(3000);
        selector.selectByValue("Honor");
        
posted on 2020-06-11 17:14  91parson  阅读(104)  评论(0编辑  收藏  举报