File size: 2,591 Bytes
658216c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import requests
from bs4 import BeautifulSoup
import time
import os
import re

# ── Configuration ──────────────────────────────────────────────
NOVEL_ID   = "146570"
BASE_URL   = "https://ixdzs.tw/read/146570/p{}.html"
START_PAGE = 1
END_PAGE   = 775
OUTPUT_DIR = r"C:\Users\Iqra\Videos\Next YT\XVI\txt_cont"
DELAY      = 1.5
# ───────────────────────────────────────────────────────────────

HEADERS = {
    "User-Agent": (
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
        "AppleWebKit/537.36 (KHTML, like Gecko) "
        "Chrome/124.0.0.0 Safari/537.36"
    ),
    "Accept-Language": "zh-TW,zh;q=0.9",
    "Referer": "https://ixdzs.tw/read/146570/",
}


def fetch_chapter(page_num):
    url = BASE_URL.format(page_num)
    resp = requests.get(url, headers=HEADERS, timeout=15)
    resp.raise_for_status()
    resp.encoding = "utf-8"
    soup = BeautifulSoup(resp.text, "html.parser")
    h3 = soup.find("h3")
    h1 = soup.find("h1")
    title = (h3 or h1).get_text(strip=True) if (h3 or h1) else f"Chapter {page_num}"
    for tag in soup.select("nav, header, footer, script, style, img, a[href], .ads"):
        tag.decompose()
    paragraphs = soup.find_all("p")
    lines = [p.get_text(strip=True) for p in paragraphs if p.get_text(strip=True)]
    if not lines:
        body = soup.body
        if body:
            lines = [ln.strip() for ln in body.get_text("\n").splitlines() if ln.strip()]
    return title, "\n\n".join(lines)


def save_chapter(page_num, title, text, out_dir):
    safe = re.sub(r'[\\/*?:"<>|]', "", title)[:80].strip()
    filename = f"{page_num:04d}_{safe}.txt"
    with open(os.path.join(out_dir, filename), "w", encoding="utf-8") as f:
        f.write(f"{title}\n\n{text}\n")
    print(f"  βœ“  {filename}")


def main():
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    print(f"Saving to {OUTPUT_DIR}\n")
    for page_num in range(START_PAGE, END_PAGE + 1):
        print(f"Fetching chapter {page_num}/{END_PAGE} ...", end=" ")
        try:
            title, text = fetch_chapter(page_num)
            save_chapter(page_num, title, text, OUTPUT_DIR)
        except requests.HTTPError as e:
            print(f"  HTTP {e.response.status_code} - skipping")
        except Exception as e:
            print(f"  Error: {e} - skipping")
        time.sleep(DELAY)
    print("\nAll done!")


if __name__ == "__main__":
    main()