报错
在进行《实验案例1:百度搜索软件测试》时发现代码跑完
assert "软件测试" in driver.title 测试报错断言期望:页面标题里包含“软件测试”。
实际结果:标题并没有包含软件测试即没有成功跳转
调试
反复确认代码编写没有错误
在AI的协助下,写了debug测试文件
from selenium import webdriver from selenium.webdriver.common.by import By import time d = webdriver.Edge() d.get("https://www.baidu.com") d.find_element(By.ID, "chat-textarea").send_keys("软件测试") d.find_element(By.ID, "chat-submit-button").click() time.sleep(3) print("title:", d.title) print("url:", d.current_url) print("窗口数:", len(d.window_handles)) print("h3 个数:", len(d.find_elements(By.XPATH, "//h3"))) print("源码含关键词:", "软件测试" in d.page_source) input("看完页面按回车关闭") # 让浏览器停住,人眼看清到底发生了什么 d.quit()运行结果如图所示
发现原因
运行结果:title:百度安全验证
原来我的搜索已经成功进行了,但百度把我拦在了安全验证页。
百度检测到我的浏览器是自动化工具(Selenium),于是弹出验证码,要求手动验证。这就是为什么标题里没有"软件测试"——因为根本没到搜索结果页,被拦在验证码页面了。
解决办法
在search()方法中添加强制等待,用于手动过验证
代码如下所示
def search(self,keyword): # # river.find_element(By.ID,"chat-textarea").send_keys("软件测试") # self.driver.find_element(*self.SEARCH_INPUT).send_keys(keyword) self.input_text(self.SEARCH_INPUT,keyword) # # driver.find_element(By.ID,"chat-submit-button").click() # self.driver.find_element(*self.SEARCH_BUTTON).click() self.click(self.SEARCH_BUTTON) # 暂停 40 秒,手动过验证码 import time time.sleep(40) # #点击后切换到新窗口 # self.switch_to_new_window() return self