获取网页标题、地址、源码及会话信息
title / current_url / page_source 三件套 + Selenium 4 新方法
driver.title · driver.current_url · driver.page_source · driver.print_page_source()读取 title 标题、current_url 当前地址、page_source 源码;Selenium 4 新方法:print_page_source / get_log。
driver.titledriver.current_urldriver.page_sourcedriver.print_page_source("page.html"),一行代码保存源码到文件
// 点击「page_source 摘要」按钮,这里会显示 HTML 前 15 行
# 页面信息获取 + Selenium 4 新方法
print("标题:", driver.title)
print("URL:", driver.current_url)
print("源码长度:", len(driver.page_source))
print("所有标签:", driver.window_handles)
print("当前句柄:", driver.current_window_handle)
print("Session:", driver.session_id)
# Selenium 4 新写法
driver.print_page_source("page.html") # 一行保存源码到文件
logs = driver.get_log("browser") # 读取浏览器控制台日志
# ✅ 实战:一次性打包成 JSON 输出
import json
info = {
"title": driver.title,
"url": driver.current_url,
"source_len": len(driver.page_source),
"handles": driver.window_handles,
"session": driver.session_id,
}
https://autotest-505.pages.dev/,用 6 个方法分别读取 title / url / source 长度 / window_handles / current_window_handle / session_id,一次性 json.dumps() 漂亮打印成 JSONif "你的关键词" in driver.title: print("✅"),再把判断封装成 check_title(keyword) 函数(复用上面的 driver)page_source 返回的是整个 HTML 字符串 —— 试用 Python 的 len()、正则、BeautifulSoup 分别统计页面有多少个 <img> 标签,并把三种方法的耗时用 time.perf_counter() 对比driver.window_handles 和 driver.current_window_handle 的区别 —— 哪个是列表?哪个是当前标签句柄?logs = driver.get_log("browser") 读取 3 种级别日志(browser / performance / driver),分别打印看看内容差异driver.print_page_source(),比自己 open().write() 更方便;current_window_handle 是切换标签时判断「我在哪」的唯一凭据