1. 程式人生 > 其它 >IDE自動化指令碼實現

IDE自動化指令碼實現

案列:開啟百度瀏覽器,在瀏覽器中搜索bing,點選搜尋,進入官網bing的搜尋目錄,在bing瀏覽器中搜索python,點選搜尋,在查到的結果中找到python官網,進入。

經過以上流程,輸出的自動化指令碼修改後如下:

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
import unittest, time, re


class Idedem(unittest.TestCase):
    def setUp(self):  # unittest開始
        self.driver = webdriver.Firefox()  # 定義驅動
        self.driver.implicitly_wait(30)  # 設定隱士等待
        self.base_url = "https://www.baidu.com/"  # 初始化url
        self.verificationErrors = []  # 異常
        self.accept_next_alert = True  # 預設設定彈框為確定
        self.switch_handle = self.switch_handle  # 自定義切換控制代碼

    def switch_handle(self):
        """切換控制代碼"""
        driver = self.driver
        headles = driver.window_handles
        driver.switch_to.window(headles[-1])

    def test_idedem(self):
        """自動化錄製指令碼流程"""
        driver = self.driver
        driver.get(self.base_url + "/")
        driver.find_element_by_id("kw").click()  # 定位搜尋框並點選
        driver.find_element_by_id("kw").clear()  # 清空
        driver.find_element_by_id("kw").send_keys("bing")  # 在搜尋框輸入bing
        driver.find_element_by_id("su").click()  # 點選百度一下
        driver.find_element_by_xpath(".//*[@id='1']/h3/a[1]").click()  # 定位bing搜尋框並點選
        self.switch_handle()  # 切換控制代碼
        driver.find_element_by_id("sb_form_q").clear()  # 清空
        driver.find_element_by_id("sb_form_q").send_keys("python")  # 在搜尋框輸入python
        driver.find_element_by_id("sb_form_go").click()  # 點擊發送
        self.switch_handle()  # 切換控制代碼
        driver.find_element_by_link_text("Welcome to Python.org").click()  # 選擇python官網進入
        print("執行成功")

    def is_element_present(self, how, what):
        """:param
        how: 如何定位元素
        what:定位元素的值是什麼
        """
        try:
            self.driver.find_element(by=how, value=what)
        except NoSuchElementException as e:
            return False
        return True

    def is_alert_present(self):
        """彈框相關操作"""
        try:
            self.driver.switch_to.alert()
        except NoAlertPresentException as e:
            return False
        return True

    def close_alert_and_get_its_text(self):
        """彈框的確認與關閉選擇"""
        try:
            alert = self.driver.switch_to.alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally:
            self.accept_next_alert = True

    def tearDown(self):  # 結束
        # self.driver.quit()
        # self.assertEqual([], self.verificationErrors)
        pass


if __name__ == "__main__":
    unittest.main()