2012-09-10 126 views
2

我對Python比較陌生。我正在嘗試使用Python Selenium Web Driver進行一些網絡自動化。 我將爲不同的場景編寫單獨的腳本:例如一個用於登錄,另一個用於檢查着陸頁上的工具提示等。Python Selenium webdriver查詢

我的問題是,我想爲我的所有測試用例使用相同的Firefox實例。所以,登錄後我的測試腳本將在同一個登錄的FireFox實例上工作。

請讓我知道如何做到這一點。

感謝,

Mohima

回答

1

不寫單獨的腳本。而是寫出不同的功能:

def login(): ... 
def check_tooltips(): ... 

如果你希望把函數放在不同的文件中,那是沒有問題的;你可以從其他導入一個模塊(例如tooltips.py):

import tooltips 
def login(): ... 
def main(): 
    login() 
    tooltips.check_tooltips() 
+1

和OP應該使用Firefox的驅動程序作爲一個全局變量或把它當作一個函數參數。 –

+0

有沒有辦法使用相同的Firefox對象編寫不同的腳本?麻煩的是有一個自動化框架..這需要單獨的腳本,並顯示每個腳本的輸出。如果我把所有東西放到一個腳本中,它就不能進入框架 –

+0

不幸的是,我不知道連接到一個開放會話的方式。這似乎是[公開問題](http://code.google.com/p/selenium/issues/detail?id=18&colspec=ID%20Stars%20Type%20Status%20Priority%20Milestone%20Owner%20Summary)。在該頁面和鏈接頁面(合併問題)上提到了一些解決方法,但我沒有嘗試過。 – unutbu

0

如果您在OOP猶豫,你也可以使用非OOP方式

# your imports 
from selenium import webdriver 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 
import csv 
import win32com.client 
import time 
import os 

driver=webdriver.Chrome() 
driver.get("your url") 
wait=WebDriverWait(driver,30) 
# select the username and password fields and enter your details and after that click the login button. after that you will see welcome page in the same instance. 
username=wait.until(EC.presence_of_element_located((By.ID, 'LoginEmailOrNickname'))) 
username.send_keys(email) 

passw=wait.until(EC.presence_of_element_located((By.ID, 'login-password'))) 
passw.send_keys(pas) 

submit=wait.until(EC.presence_of_element_located((By.ID, 'SignInButton'))) 
submit.click() 


time.sleep(5) 

# here comes welcome page after login 
mykijiji=wait.until(EC.presence_of_element_located((By.LINK_TEXT, 'My Kijiji'))) 
mykijiji.click() 
1

可以使用@classmethod裝飾。所以例如你的第一個測試驗證登錄功能,比第二個測試驗證例如搜索按鈕或其他東西等等,所有這些都使用一個瀏覽器實例。

下面我使用python 2.7和單元測試

import unittest 
from selenium import webdriver 

class HomePage(unittest.TestCase): 

    @classmethod 
    def setUpClass(cls): 
     cls.selenium = webdriver.Firefox() 
     cls.selenium.maximize_window() 

    def test_login(self): 
     self.selenium.get('http://...') 
     self.selenium.find_element_by_id() 
     #and so on 

    def test_search_btn(self): 
     pass 

    @classmethod 
    def tearDownClass(cls): 
     cls.selenium.quit() 

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