获取网页标题、地址、源码及会话信息等操作
演示 Selenium 提供的 6 种浏览器状态读取方式,是做断言、调试、日志的基础工具。点击按钮即可实时读取当前 demo 页面的各项属性。
6 个核心属性/方法:
driver.title → 页面标签标题,做跳转断言最常用driver.current_url → 当前 URL,比 title 精确,能查 query 参数driver.page_source → HTML 源码字符串(不包含 iframe 内容)driver.window_handles → 所有标签句柄列表(多标签切换必备)driver.current_window_handle → 当前标签句柄(单字符串)driver.session_id → 会话 ID,同一个 driver 生命周期内不变⚠️ 注意:page_source 返回的是初始 HTML,不是 JS 渲染后的 DOM!SPA 页面要用 execute_script('return document.documentElement.outerHTML')。
driver.title / current_url / page_source / session_id / capabilities / name
# 快速参考 driver.get("https://example.com") assert "Example" in driver.title assert "example.com" in driver.current_url assert driver.session_id assert "chrome" == driver.capabilities['browserName'] assert "<html" in driver.page_source.lower()
get() 后断言 driver.title 包含预期文案、driver.current_url 包含目标域名driver.session_id 非空,driver.capabilities['browserName'] 等于 chromedriver.page_source,断言其中包含 <html 标签与页面标题关键字
操作步骤:
① driver.get("目标URL") 后获取 driver.title 断言包含预期文案,driver.current_url 断言包含目标域名。
② 断言 driver.session_id 非空,driver.capabilities['browserName'] 等于 chrome。
③ 获取 driver.page_source 断言包含 <html 标签与页面标题关键字。
💡 driver.page_source 返回完整 HTML 源码,通常包含 <html、<head、<body 等标签。
# 练习 5 参考答案 from selenium import webdriver driver = webdriver.Chrome() driver.get("https://example.com") # ① 各种信息获取与断言 title = driver.title assert title is not None and "Example" in title, f"title 不符合预期: {title}" current_url = driver.current_url assert "example.com" in current_url, f"url 不符合预期: {current_url}" session_id = driver.session_id assert session_id, "session_id 为空" browser_name = driver.capabilities['browserName'] assert browser_name == "chrome", f"browserName 不符合预期: {browser_name}" # ② page_source 断言 source = driver.page_source assert "<html" in source.lower(), "page_source 不包含 <html" assert "Example Domain" in source, "page_source 不包含标题文本" driver.quit() print("✅ 练习 5 所有断言通过!")