| import requests, sys, json, lzma, os, time
|
| from bs4 import BeautifulSoup
|
| from multiprocessing.pool import Pool
|
|
|
| DOMAIN = "https://thichtruyen.vn"
|
|
|
| t = open("cats.txt", "rt").read()
|
| cats = []
|
| for idx, x in enumerate(t.strip().split("\n\n")):
|
| u, t = x.split("\n")
|
| u = DOMAIN + u
|
|
|
| cats.append({"title": t, "url": u, "_id": idx})
|
|
|
|
|
| def crawl(cat):
|
| cat_id = cat["_id"]
|
| cat_url = cat["url"]
|
| cat_file = f"cats/{cat_id}.jsonl"
|
|
|
| crawled_pages = set()
|
| if os.path.exists(cat_file):
|
| with open(cat_file, "rt") as fin:
|
| for line in fin:
|
| crawled_pages.add(json.loads(line)["page"])
|
|
|
| for page in range(1, 9999):
|
| if page in crawled_pages: continue
|
| page_url = f"{cat_url}?page={page}"; print(page_url)
|
| r = requests.get(page_url)
|
| soup = BeautifulSoup(r.content, "html.parser")
|
|
|
| stories = []
|
| for item in soup.select("#tab-over .view-category-item-infor"):
|
| a = item.select("a")[0]
|
| url = DOMAIN + a["href"]
|
| title = a.select("h3")[0].text.strip()
|
| print(url, title)
|
| stories.append({
|
| "title": title,
|
| "url": url,
|
| "cat": cat["title"],
|
| "page": page,
|
| })
|
|
|
| with open(cat_file, "at") as fout:
|
| for story in stories:
|
| fout.write(json.dumps(story, ensure_ascii=False) + "\n")
|
|
|
| if len(stories) == 0: break
|
| time.sleep(1)
|
|
|
|
|
| with Pool() as pool:
|
| for _ in pool.imap_unordered(crawl, cats):
|
| False
|
|
|