您可能需要在多种情况下针对不同的浏览器(例如Firefox,Chrome,Internet Explorer,Edge)测试代码。跨不同浏览器测试网站的做法称为自动浏览器测试。要使用Selenium自动化测试执行自动浏览器测试,您应该在单元测试代码或pytest
代码中合并对这些浏览器的选择性处理。下面显示了一个代码片段(利用pytest
)来处理多个浏览器:
''' 导入必要的包和类 '''
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from time import sleep
@pytest.fixture(params=["chrome", "firefox"],scope="class")
def driver_init(request):
if request.param == "chrome":
# 搞点事情
if request.param == "firefox":
# 搞定事情
yield
web_driver.close()
...........
...........
使用CSS定位器
使用Selenium执行测试自动化时,在页面上定位Web元素是自动化脚本的基础。如果您想基于特定种类的Web元素(如Tag,Class,ID等)的存在来执行条件执行,则可以使用find_elements _ *** API。下面提到其中一些
-
find_elements_by_class_name():按类名称查找元素
-
find_elements():按策略和定位器查找元素
-
find_element_by_link_text():通过链接文本查找元素
-
find_element_by_partial_link_text():通过链接文本的部分匹配来查找元素
下面显示的是find_element_by_partial_link_t