Update main.py
Browse files
main.py
CHANGED
|
@@ -1,33 +1,47 @@
|
|
| 1 |
-
from fastapi import FastAPI
|
| 2 |
-
from playwright.async_api import async_playwright
|
| 3 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
app = FastAPI()
|
| 6 |
|
| 7 |
-
@app.
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
url = "https://civitai.com/models/1055452/akashicpulse"
|
| 11 |
output_path = "akashicpulse.mhtml"
|
| 12 |
|
| 13 |
try:
|
| 14 |
-
|
| 15 |
-
browser =
|
| 16 |
-
page =
|
| 17 |
-
|
| 18 |
|
| 19 |
-
cdp_session =
|
| 20 |
-
snapshot =
|
| 21 |
-
|
| 22 |
-
await browser.close()
|
| 23 |
|
| 24 |
with open(output_path, "w", encoding="utf-8") as f:
|
| 25 |
f.write(snapshot)
|
| 26 |
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
| 28 |
except Exception as e:
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
return {"message": "Check logs for MHTML creation results."}
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
from fastapi import FastAPI
|
| 3 |
+
from playwright.sync_api import sync_playwright
|
| 4 |
+
# ↑ 同期版だと "It looks like you are using Playwright Sync API inside the asyncio loop"
|
| 5 |
+
# と怒られる場合がある。
|
| 6 |
+
# その場合は下記の async版を使い、エンドポイントも async def にする。
|
| 7 |
+
# from playwright.async_api import async_playwright
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
| 11 |
+
@app.get("/")
|
| 12 |
+
def read_root():
|
| 13 |
+
return {
|
| 14 |
+
"message": "Visit /save_mhtml to capture MHTML. Then check the dev mode to see if the file is there."
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
@app.get("/save_mhtml")
|
| 18 |
+
def save_mhtml():
|
| 19 |
+
"""
|
| 20 |
+
/save_mhtml にアクセスしたタイミングで外部URLを読み込み、MHTMLを保存する。
|
| 21 |
+
ここで失敗しても起動時には関係ないので、Devモードが落ちるリスクが減る。
|
| 22 |
+
"""
|
| 23 |
url = "https://civitai.com/models/1055452/akashicpulse"
|
| 24 |
output_path = "akashicpulse.mhtml"
|
| 25 |
|
| 26 |
try:
|
| 27 |
+
with sync_playwright() as p:
|
| 28 |
+
browser = p.chromium.launch(headless=True)
|
| 29 |
+
page = browser.new_page()
|
| 30 |
+
page.goto(url, wait_until="networkidle", timeout=60000)
|
| 31 |
|
| 32 |
+
cdp_session = page.context.new_cdp_session(page)
|
| 33 |
+
snapshot = cdp_session.send("Page.captureSnapshot", {"format": "mhtml"})
|
| 34 |
+
browser.close()
|
|
|
|
| 35 |
|
| 36 |
with open(output_path, "w", encoding="utf-8") as f:
|
| 37 |
f.write(snapshot)
|
| 38 |
|
| 39 |
+
return {
|
| 40 |
+
"status": "success",
|
| 41 |
+
"message": f"MHTML saved to {os.path.abspath(output_path)}"
|
| 42 |
+
}
|
| 43 |
except Exception as e:
|
| 44 |
+
return {
|
| 45 |
+
"status": "error",
|
| 46 |
+
"message": str(e)
|
| 47 |
+
}
|
|
|