我正在尝试运行此代码以在 Chrome 和 Firefox 中执行一些操作,但是当我运行测试运行程序时,Chrome 启动并且测试用例在 Chrome 中失败,然后 Firefox 打开并且测试用例在 Firefox 中工作正常。
我已经尝试了 for 循环和一些没有用的东西。
这是我的代码:
from selenium import webdriver as wd
import pytest
import time
Chrome=wd.Chrome(executable_path=r"C:\Chrome\chromedriver.exe")
Firefox=wd.Firefox(executable_path=r"C:\geckodriver\geckodriver.exe")
class TestLogin():
@pytest.fixture()
def setup1(self):
browsers=[Chrome, Firefox]
for i in browsers:
self.driver= i
i.get("https://www.python.org")
time.sleep(3)
yield
time.sleep(3)
self.driver.close()
def test_Python_website(self,setup1):
self.driver.find_element_by_id("downloads").click()
time.sleep(3)
最佳答案
您应该等待元素,而不是显式sleep
:
from selenium import webdriver as wd
from selenium.webdriver.support import expected_conditions as EC
import pytest
import time
Chrome=wd.Chrome(executable_path=r"C:\Chrome\chromedriver.exe")
Firefox=wd.Firefox(executable_path=r"C:\geckodriver\geckodriver.exe")
class TestLogin():
@pytest.fixture()
def setup1(self):
browsers = [Chrome, Firefox]
for i in browsers:
self.driver = i
i.get("https://www.python.org")
yield
self.driver.quit()
def test_Python_website(self, setup1):
wait = WebDriverWait(self.driver, 10)
downloads = wait.until(EC.element_to_be_clickable(By.ID, "downloads"))
downloads.click()
注意:您可能需要 self.driver.quite()
,因为这将关闭窗口并导致浏览器进程也关闭。调用 self.driver.close()
只会关闭窗口,但会在测试完成后让 firefox.exe 或 chrome.exe 进程在内存中运行。
关于python - 使用 Selenium 和 Python 进行跨浏览器测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58644933/