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

yuvru6vn  于 2023-05-11  发布在  Go
关注(0)|答案(1)|浏览(309)

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

Python原创项目

如果所有内容都在一个Python文件中,那么很简单:

test_home.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中进行测试时,在两个浏览器中,当最初连接到https://localhost/home时,您会收到错误消息NET::ERR_CERT_COMMON_NAME_INVALID,因此我必须确认前进到登录页面,登录然后检查主页上的文本。此代码将从Chrome开始,然后在Edge中继续执行相同的步骤。
现在,这段代码非常低效:它基本上是将相同的代码加倍。我还计划创建更多的测试,将涉及测试网站的更多方面,这意味着登录过程将是必要的每一个测试我执行。

Python项目更新

作为一个朋友的建议,我应该为这个test_ python文件创建一些函数来调用。

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

Chrome和Edge Functions的libraries文件夹(它们通常非常相似)即使这样,我认为它们可能应该组合在一起,但我有一种感觉,试图从同一个库调用2个不同的WebDrivers(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_home.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继续当前的驱动程序时。然而,当我尝试在__init__中包含self.driver = webdriver.Chrome("C:\Drivers\chromedriver_win32\chromedriver.exe")时,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"),以便在运行connectfind_string函数时只运行一次?有没有更好的方法我应该调用WebDriver?

flseospp

flseospp1#

__init__中定义self.driver,并且仅定义一次。
您可以使用__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_home.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!")

edge和chrome一码通

  • 我推荐这个 *

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 driver_name == "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_home.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!")

相关问题