import csv
import random
import pytest
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options # 添加 Options 模块
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def read_csv():
with open('search_data.csv', 'r', encoding='utf-8') as f:
return list(csv.DictReader(f))
@pytest.mark.parametrize("data", read_csv())
def test_search(data):
# 设置 Firefox 选项(防反爬)
options = Options()
options.set_preference("general.useragent.override",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
# 替换为本地 geckodriver 的路径
service = Service(r'F:\PythonProject\rjcs6\geckodriver.exe') # 使用本地路径
driver = webdriver.Firefox(service=service, options=options) # 传入 options 参数
driver.get("https://github.com")
wait = WebDriverWait(driver, 10)
# 点击搜索按钮,展开输入框
search_button = wait.until(
EC.element_to_be_clickable((By.XPATH, "//button[@aria-label='Search or jump to…']"))
)
search_button.click()
# 等待搜索框加载
search_box = wait.until(
EC.presence_of_element_located((By.NAME, "query-builder-test"))
)
# 输入关键词并提交
search_box.send_keys(data["keyword"])
search_box.submit()
# 根据预期结果验证
if data["expected_result"] == "有结果":
assert "Your search did not match any" not in driver.page_source
else:
try:
# 使用XPath检查是否存在 "没有匹配的仓库" 提示
wait.until(
EC.presence_of_element_located(
(By.XPATH, "//h3[contains(text(), 'Your search did not match any')]")
)
)
# 如果找到了该提示元素,说明没有结果
no_result = True
except:
# 如果没有找到该提示元素,说明有结果
no_result = False
# 断言结果是否符合预期
assert no_result, f"预期无结果,但搜索 '{data['keyword']}' 显示有结果。"
driver.quit()
# 延时,防止触发访问限制
time.sleep(random.randint(30, 60))