"""Offline Playwright Chromium lab for Chapter 13: Playwright File Operations."""
import json
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from playwright.sync_api import sync_playwright, expect
DOWNLOAD_CONTENT = b"Playwright Offline Report v1\nline2=ok\n"
class FileHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
return
def _send(self, code, body, content_type="text/html; charset=utf-8", extra_headers=None):
data = body.encode("utf-8") if isinstance(body, str) else body
self.send_response(code)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
if extra_headers:
for k, v in extra_headers.items():
self.send_header(k, v)
self.end_headers()
self.wfile.write(data)
def do_GET(self):
if self.path == "/upload":
self._send(
200,
"<!doctype html><html><head><title>File Ops</title></head><body>"
"<input id='single' type='file' />"
"<input id='multi' type='file' multiple />"
"<button id='file-submit' onclick=\""
"const f1=[...document.getElementById('single').files].map(f=>f.name);"
"const f2=[...document.getElementById('multi').files].map(f=>f.name);"
"document.getElementById('uploaded-files').textContent=(f1.length?f1:f2).join(',');"
"\">提交</button>"
"<div id='uploaded-files'></div>"
"<button id='upload' onclick=\"document.getElementById('hidden-file').click()\">选择PDF</button>"
"<input id='hidden-file' type='file' style='display:none' onchange=\""
"const f=this.files[0];"
"document.getElementById('chooser-out').textContent=f?`${f.name}:${f.size}`:'empty';"
"\" />"
"<div id='chooser-out'></div>"
"<a id='downloadButton' href='/download/report.txt'>下载报告</a>"
"</body></html>",
)
elif self.path == "/download/report.txt":
self._send(
200,
DOWNLOAD_CONTENT,
"text/plain; charset=utf-8",
{"Content-Disposition": 'attachment; filename="report.txt"'},
)
else:
self._send(404, "not found")
def launch_browser(p):
for kwargs in (dict(channel="chrome", headless=True), dict(channel="msedge", headless=True), dict(headless=True)):
try:
return p.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("No local Chromium executable found")
def main():
server = ThreadingHTTPServer(("127.0.0.1", 0), FileHandler)
port = server.server_address[1]
base_url = f"http://127.0.0.1:{port}"
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
cases = []
try:
with tempfile.TemporaryDirectory() as tmpdir, sync_playwright() as p:
tmp = Path(tmpdir)
f_avatar = tmp / "avatar.png"
f_avatar.write_bytes(b"\x89PNG\r\n\x1a\navatar")
f1 = tmp / "1.png"
f1.write_bytes(b"\x89PNG\r\n\x1a\n1")
f2 = tmp / "2.png"
f2.write_bytes(b"\x89PNG\r\n\x1a\n2")
f_pdf = tmp / "test.pdf"
f_pdf.write_bytes(b"%PDF-1.4 demo")
browser = launch_browser(p)
# Case 1: page.set_input_files single, locator.set_input_files multi & FilePayload, and [] clear
ctx1 = browser.new_context()
page1 = ctx1.new_page()
page1.goto(f"{base_url}/upload")
page1.set_input_files("#single", str(f_avatar))
page1.click("#file-submit")
expect(page1.locator("#uploaded-files")).to_have_text("avatar.png")
single_name = page1.locator("#uploaded-files").text_content()
page1.set_input_files("#single", [])
cleared_len = page1.locator("#single").evaluate("el => el.files.length")
multi = page1.locator("#multi")
multi.set_input_files([str(f1), str(f2)])
page1.click("#file-submit")
multi_names = page1.locator("#uploaded-files").text_content()
multi.set_input_files({"name": "mem.txt", "mimeType": "text/plain", "buffer": b"hello"})
payload_name = multi.evaluate("el => el.files[0].name")
ctx1.close()
actual1 = {
"single_name": single_name,
"cleared_len": cleared_len,
"multi_names": multi_names,
"payload_name": payload_name,
}
expected1 = {
"single_name": "avatar.png",
"cleared_len": 0,
"multi_names": "1.png,2.png",
"payload_name": "mem.txt",
}
cases.append(dict(name="upload_single_multi_and_clear", expected=expected1, actual=actual1, passed=actual1 == expected1))
# Case 2: expect_file_chooser + file_chooser.set_files
ctx2 = browser.new_context()
page2 = ctx2.new_page()
page2.goto(f"{base_url}/upload")
with page2.expect_file_chooser() as fc_info:
page2.click("button#upload")
fc = fc_info.value
fc.set_files(str(f_pdf))
expect(page2.locator("#chooser-out")).to_have_text(f"test.pdf:{len(b'%PDF-1.4 demo')}")
chooser_text = page2.locator("#chooser-out").text_content()
ctx2.close()
actual2 = {"chooser_out": chooser_text}
expected2 = {"chooser_out": "test.pdf:13"}
cases.append(dict(name="file_chooser_event_upload", expected=expected2, actual=actual2, passed=actual2 == expected2))
# Case 3: expect_download, save_as, path, url, suggested_filename
ctx3 = browser.new_context(accept_downloads=True)
page3 = ctx3.new_page()
page3.goto(f"{base_url}/upload")
with page3.expect_download() as dl_info:
page3.click("a#downloadButton")
dl = dl_info.value
saved_path = tmp / "downloads" / "report.txt"
dl.save_as(str(saved_path))
default_path = dl.path()
actual3 = {
"suggested_filename": dl.suggested_filename,
"url_suffix": dl.url.endswith("/download/report.txt"),
"default_path_exists": bool(default_path and Path(default_path).exists()),
"saved_bytes_match": saved_path.read_bytes() == DOWNLOAD_CONTENT,
}
expected3 = {
"suggested_filename": "report.txt",
"url_suffix": True,
"default_path_exists": True,
"saved_bytes_match": True,
}
ctx3.close()
cases.append(dict(name="download_save_as_and_metadata", expected=expected3, actual=actual3, passed=actual3 == expected3))
# Case 4: Full-page screenshot, locator screenshot, trace zip export & video-disabled check
ctx4 = browser.new_context(viewport={"width": 640, "height": 480})
ctx4.tracing.start(screenshots=True, snapshots=True)
page4 = ctx4.new_page()
page4.goto(f"{base_url}/upload")
full_shot = tmp / "home.png"
elem_shot = tmp / "btn.png"
page4.screenshot(path=str(full_shot), full_page=True)
page4.locator("#file-submit").screenshot(path=str(elem_shot))
video_without_config = page4.video
trace_zip = tmp / "trace.zip"
ctx4.tracing.stop(path=str(trace_zip))
ctx4.close()
actual4 = {
"full_shot_png": full_shot.read_bytes().startswith(b"\x89PNG"),
"elem_shot_png": elem_shot.read_bytes().startswith(b"\x89PNG"),
"trace_zip_valid": trace_zip.exists() and trace_zip.read_bytes().startswith(b"PK\x03\x04"),
"video_none_without_record_option": video_without_config is None,
}
expected4 = {
"full_shot_png": True,
"elem_shot_png": True,
"trace_zip_valid": True,
"video_none_without_record_option": True,
}
cases.append(dict(name="screenshots_trace_and_video_option", expected=expected4, actual=actual4, passed=actual4 == expected4))
browser.close()
finally:
server.shutdown()
server.server_close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/playwright-file-operations-lab/explore-file-operations.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-file-operations.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a602.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a612.zip