import csv
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from webdriver_manager.microsoft import EdgeChromiumDriverManager
# 读取CSV文件内容
def read_csv():
with open('search_data.csv', 'r', encoding='utf-8') as f:
return list(csv.DictReader(f))
# 使用 pytest 的参数化功能,传入 CSV 中的每一行数据
@pytest.mark.parametrize("data", read_csv())
def test_search(data):
# 设置 Edge 浏览器选项,启动时不使用现有的用户数据(清除缓存)
options = Options()
options.add_argument("--incognito") # 使用无痕模式避免保存任何缓存或登录状态
options.add_argument("--disable-extensions") # 禁用扩展
# 启动 Edge 浏览器
service = Service(EdgeChromiumDriverManager().install())
driver = webdriver.Edge(service=service, options=options)
try:
# 直接访问 GitHub 搜索页面
search_url = f"https://github.com/search?q={data['keyword']}"
driver.get(search_url)
# 等待页面加载完成(这里可以根据实际情况增加等待时间)
driver.implicitly_wait(5)
# 根据预期结果验证
if data["expected_result"] == "有结果":
assert "No results matched" not in driver.page_source
else:
assert "No results matched" in driver.page_source
# 输出结果
print("Selenium-有结果")
except Exception as e:
print("InvalidKeyword123-无结果", e)
finally:
# 最后关闭浏览器
driver.quit()
浙公网安备 33010602011771号