Python Selenium:为多个函数调用调用相同的 WebDriver

问题描述 投票:0回答:1

我想创建 2 个测试(基本上是相同的测试,但 1 个在 Chrome 中,另一个在 Edge 中)。只是简单地连接到网页并确认页面上的一些文本。

原创Python项目

如果一切都在 1 个 Python 文件中,那就很简单了:

test_homepage.py

import time

from selenium import webdriver
from selenium.webdriver.common.by import By

# ----------- Connection Test (Chrome) ---------------------------------------------------------------
url = "https://localhost/home"
driver=webdriver.Chrome("C:\Drivers\chromedriver_win32\chromedriver.exe")
driver.get(url)

# "Your connection is not private"
driver.find_element(By.ID, "details-button").click() # Click the "Advanced" button
time.sleep(1)
driver.find_element(By.ID, "proceed-link").click() # Click the "Proceed to localhost (unsafe)" link
time.sleep(1)

# Login Page
driver.find_element(By.ID, "userNameInput").send_keys("TestUser")
driver.find_element(By.ID, "passwordInput").send_keys("Password123")
driver.find_element(By.ID, "submitButton").click()
time.sleep(1)

# Search for text on the Homepage to confirm reaching the destination
get_source = driver.page_source
search_text = "Welcome to the Homepage!"
driver.close()

try:
    if (search_text in get_source):
        assert True
        print("Chrome Test: Passed")
    else:
        assert False
except:
    print("Chrome Test: Failed")

# ----------- Connection Test (Edge) ---------------------------------------------------------------
driver=webdriver.Edge("C:\Drivers\edgedriver_win64\msedgedriver.exe")
driver.get(url)

driver.find_element(By.ID, "details-button").click() # Click the "Advanced" button
time.sleep(1)
driver.find_element(By.ID, "proceed-link").click() # Click the "Proceed to localhost (unsafe)" link
time.sleep(1)

# Login Page
driver.find_element(By.ID, "userNameInput").send_keys("TestUser")
driver.find_element(By.ID, "passwordInput").send_keys("Password123")
driver.find_element(By.ID, "submitButton").click()
time.sleep(1)

# Search for text on the Homepage to confirm reaching the destination
get_source = driver.page_source
search_text = "Welcome to the Homepage!"
driver.close()

try:
    if (search_text in get_source):
        assert True
        print("Edge Test: Passed")
    else:
        assert False
except:
    print("Edge Test: Failed")

在 Python Selenium 中进行测试时,在两种浏览器中,最初连接到

NET::ERR_CERT_COMMON_NAME_INVALID
时都会收到错误消息
https://localhost/home
,因此我必须确认前进到登录页面,登录然后检查主页上的文本。此代码将从 Chrome 开始,然后在 Edge 中执行相同的步骤。

现在,这段代码效率很低:它基本上是将相同的代码加倍。我还计划创建更多测试,涉及测试网站的更多方面,这意味着我执行的每个测试都需要登录过程。

更新的 Python 项目

根据朋友的建议,我应该为这个

test_
python文件创建一些函数来调用。

libraries/
├── chrome.py
├── edge.py
tests/
├── test_homepage.py

Chrome 和 Edge Functions 的

libraries
文件夹(它们通常非常相似......即便如此,我认为它们可能应该合并,但我有一种感觉,试图从同一个调用 2 个不同的 WebDriver库 python 文件将变得困难),然后是每个测试的
tests
文件夹(我想确保每个测试都在 Chrome 和 Edge 中执行)。以下是我的 Python 项目的更新:

chrome.py

import time

from selenium import webdriver
from selenium.webdriver.common.by import By

class WebChrome:
    def __init__(self):
        print("")
    
    def connect(self, username: str, password: str):
        self.driver = webdriver.Chrome("C:\Drivers\chromedriver_win32\chromedriver.exe")
        self.driver.get("https://localhost/homepage")
        time.sleep(1)
        
        get_source = self.driver.page_source
        not_private = "Your connection is not private"
        if (not_private in get_source):
            # NET::ERR_CERT_COMMON_NAME_INVALID
            self.driver.find_element(By.ID, "details-button").click()
            self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # Scrolls to the bottom of the page
            time.sleep(1)
            self.driver.find_element(By.ID, "proceed-link").click()
            time.sleep(1)
        
        get_source = self.driver.page_source
        login_page = "Login Page"
        if (login_page in get_source):
            self.driver.find_element(By.ID, "userNameInput").send_keys(username)
            self.driver.find_element(By.ID, "passwordInput").send_keys(password)
            self.driver.find_element(By.ID, "submitButton").click()
            time.sleep(1)

    def find_string(self, search_text: str):
        self.driver = webdriver.Chrome("C:\Drivers\chromedriver_win32\chromedriver.exe")
        get_source = self.driver.page_source
        self.driver.close()

        try:
            if (search_text in get_source):
                assert True
                print("Chrome Test: Passed")
            else:
                assert False
        except:
            print("Chrome Test: Failed")

(当我让 Chrome 正常工作时,我会去

edge.py
。我还想更新我的代码,以便在继续下一个之前查看它是否在“您的连接不是私人的”或“登录页面”上步骤,并且该代码看起来可以正常工作。)

test_homepage.py

from libraries.chrome import WebChrome
from selenium import webdriver

# ----------- Connection Test (Chrome) ---------------------------------------------------------------
WebChrome().connect("TestUser", "Password123")
WebChrome().find_string("Welcome to the Homepage!")

现在,

connect
功能看起来像我预期的那样工作。然而,一旦 Selenium 到达主页,当前的 Chrome 浏览器就会关闭,新的 Chrome 浏览器会在结束前出现一毫秒,导致测试失败。

我假设正在发生的事情:当我打电话给

find_string
时,我正在开始一个新的会话,因为我被称为
self.driver
。我真的只想在
connect
函数中调用WebDriver,然后当我调用
find_string
时继续当前的驱动程序。但是,当我尝试在
self.driver = webdriver.Chrome("C:\Drivers\chromedriver_win32\chromedriver.exe")
中包含
__init__
时,Selenium 会打开 2 个 Chrome 浏览器(第一个未使用)并且我遇到错误(恐怕我不太了解构造函数:我真正知道的
__init__
是否应该在课程或程序启动后立即运行代码?)。我还尝试将
self.driver = webdriver.Chrome("C:\Drivers\chromedriver_win32\chromedriver.exe")
移动到
WebChrome
类的开头,在 2 个函数之前,以及从
find_string
中删除代码,但这会在程序运行时导致语法错误:
AttributeError: 'WebChrome' object has no attribute 'driver'

这是我的问题:我应该在哪里调用

self.driver = webdriver.Chrome("C:\Drivers\chromedriver_win32\chromedriver.exe")
以便当我同时运行
connect
find_string
函数时它只会运行一次?还有我应该调用 WebDriver 的更好方法吗?

python google-chrome selenium-webdriver webdriver microsoft-edge
1个回答
0
投票

self.driver
中定义
__init__
并且只定义一次。
假设您只需要连接一次,您可以将
__init__
用作
connect
函数。
您每次都在创建一个新对象。您必须为单个测试定义一次
WebChrome

截至目前,无需传递 exe 路径,只需使用
webdriver.Chrome()
webdriver.Edge()

edge 和 chrome 的代码不同

chrome.py

import time

from selenium import webdriver
from selenium.webdriver.common.by import By

class WebChrome:
    def __init__(self, username: str, password: str):
        self.driver = webdriver.Chrome()
        self.driver.get("https://localhost/homepage")
        time.sleep(1)
        
        get_source = self.driver.page_source
        not_private = "Your connection is not private"
        if (not_private in get_source):
            # NET::ERR_CERT_COMMON_NAME_INVALID
            self.driver.find_element(By.ID, "details-button").click()
            self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # Scrolls to the bottom of the page
            time.sleep(1)
            self.driver.find_element(By.ID, "proceed-link").click()
            time.sleep(1)
        
        get_source = self.driver.page_source
        login_page = "Login Page"
        if (login_page in get_source):
            self.driver.find_element(By.ID, "userNameInput").send_keys(username)
            self.driver.find_element(By.ID, "passwordInput").send_keys(password)
            self.driver.find_element(By.ID, "submitButton").click()
            time.sleep(1)

    def find_string(self, search_text: str):
        get_source = self.driver.page_source
        self.driver.close()

        try:
            if (search_text in get_source):
                assert True
                print("Chrome Test: Passed")
            else:
                assert False
        except:
            print("Chrome Test: Failed")

test_homepage.py

from libraries.chrome import WebChrome
from selenium import webdriver

# ----------- Connection Test (Chrome) ---------------------------------------------------------------
test_obj = WebChrome("TestUser", "Password123")
test_obj.find_string("Welcome to the Homepage!")

边缘和铬的一个代码

我推荐这个

chrome_and_edge.py
(只改变

__init__
函数)

class WebBrowser:
    def __init__(self, username: str, password: str,driver_name: str):
        if driver_name == "chrome":
            self.driver = webdriver.Chrome()
        elif "edge":
            self.driver = webdriver.Edge()
        self.driver.get("https://localhost/homepage")
        time.sleep(1)
        else:
           print("Enter either chrome or edge only!")
           #raise some error

test_homepage.py

from libraries.chrome import WebChrome
from selenium import webdriver

# ----------- Connection Test (Chrome) ---------------------------------------------------------------
test_obj = WebChrome("TestUser", "Password123","chrome")
test_obj.find_string("Welcome to the Homepage!")

# ----------- Connection Test (Edge) ---------------------------------------------------------------
test_obj = WebChrome("TestUser", "Password123","edge")
test_obj.find_string("Welcome to the Homepage!")
© www.soinside.com 2019 - 2024. All rights reserved.