| import requests, sys, json, lzma, os, time
|
| from bs4 import BeautifulSoup
|
| import trafilatura
|
| from multiprocessing import Process
|
| from multiprocessing.pool import Pool
|
|
|
| DOMAIN = "https://thichtruyen.vn"
|
|
|
| stories = []
|
| with lzma.open("3-stories.jsonl.xz", "rt") as fin:
|
| for idx, line in enumerate(fin):
|
| data = json.loads(line)
|
| data["_id"] = idx
|
| stories.append(data)
|
| print(len(stories), flush=True)
|
|
|
|
|
| def get_content(url):
|
| print("get_content", url, flush=True)
|
| r = requests.get(url)
|
| soup = BeautifulSoup(r.content, "html.parser")
|
| try:
|
| content = soup.select(".story-detail-content")[0]
|
| content = trafilatura.extract(str(content), output_format='txt')
|
| return content
|
| except:
|
| with open("ERRORS.txt", "at") as f: f.write(url + "\n")
|
| return None
|
|
|
| def crawl(story):
|
| story_id = story["_id"]
|
| chapters_file = f"stories/{story_id}_chapters.jsonl.xz"
|
| new_chapters_file = f"stories/{story_id}_chapters.jsonl"
|
|
|
| crawled_urls = set()
|
| if os.path.exists(chapters_file):
|
|
|
| try:
|
| with open(new_chapters_file, "wt") as fout:
|
| with lzma.open(chapters_file, "rt") as fin:
|
| for line in fin:
|
| data = json.loads(line)
|
| if len(data["content"]) <= 200: continue
|
| url = data["url"]
|
| if url not in crawled_urls:
|
| crawled_urls.add(url)
|
| fout.write(line)
|
| except:
|
| crawled_urls = set()
|
| os.remove(chapters_file)
|
| os.remove(new_chapters_file)
|
|
|
| os.remove(chapters_file)
|
|
|
| elif os.path.exists(new_chapters_file):
|
| with open(new_chapters_file, "rt") as fin:
|
| for line in fin:
|
| data = json.loads(line)
|
| if len(data["content"]) <= 200: continue
|
| url = data["url"]
|
| if url not in crawled_urls:
|
| crawled_urls.add(url)
|
|
|
| chapters = story["chapters"]
|
| problems = 0
|
|
|
| for chapter in chapters:
|
| url = chapter["url"]
|
| if url not in crawled_urls:
|
| crawled_urls.add(url)
|
| content = get_content(DOMAIN + url)
|
| if content and len(content) > 200:
|
| chapter["content"] = content
|
| with open(new_chapters_file, "at") as fout:
|
| fout.write(json.dumps(chapter, ensure_ascii=False) + "\n")
|
| else:
|
| problems += 1
|
|
|
| if problems > len(chapters) // 4:
|
| with open("PROBLEMS.txt", "at") as f:
|
| f.write(story["url"] + "\n")
|
|
|
| count = 0
|
| with Pool() as pool:
|
| for _ in pool.imap_unordered(crawl, stories):
|
| count += 1
|
| print(count, "/", len(stories), flush=True)
|
|
|