├── README.md ├── LICENSE ├── .gitignore └── novel_fetch.py /README.md: -------------------------------------------------------------------------------- 1 | # naronovel-fetch 2 | 『小説家になろう』の小説全文を取得する。 3 | 4 | ## 『小説家になろう』について 5 | [『小説家になろう』](https://syosetu.com/)とはウェブ小説を掲載している小説投稿サイトであり、色んな面白い小説が無料で読めちゃうすごいサイトです。 6 | 7 | ## Nコードについて 8 | Nコードとは『小説家になろう』における小説の管理番号です。Nコードは小説閲覧ページのURL`https://ncode.syosetu.com/n○○/`のn○○などに入っており、小説情報でも確認することができます。例えば、[『転生したらスライムだった件』](https://ncode.syosetu.com/n6316bn/)なら「n6316bn」、[『Re:ゼロから始める異世界生活』](https://ncode.syosetu.com/n2267be/)なら「n2267be」です。 9 | 10 | ## 使い方 11 | `fetch_novel.py`を次のように実行すれば指定の小説の全文が取得されます。なお、二回目以降の実行ではすでにローカルに保存されている部分と『小説家になろう』で公開されている部分の差分のみが取得されます。 12 | 13 | ``` 14 | python fetch_novel.py ncode [--reset] 15 | ```` 16 | 17 | * ncode: 取得したい小説のNコード 18 | * --reset, -r: すでに保存されている部分をすべて破棄し、改めて全部分を取得する 19 | 20 | ## 保存場所 21 | `fetch_novel.py`を実行すると、`fetch_novel.py`と同じディレクトリ内に指定のNコードを名前としてもつディレクトリが新たに生成され、その中に各部分がそれぞれ個別ファイルとして保存されます。 22 | 23 | * 『Re:ゼロから始める異世界生活』の場合 24 | 25 | ``` 26 | . 27 | ├── fetch_novel.py 28 | └── n2267be 29 | ├── n2267be_1.txt 30 | ├── n2267be_2.txt 31 | : 32 | : 33 | ``` 34 | 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 scol 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /novel_fetch.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import time 4 | import re 5 | from urllib import request 6 | from argparse import ArgumentParser 7 | from bs4 import BeautifulSoup 8 | 9 | # このファイルがあるディレクトリ 10 | dir_base = os.path.dirname(os.path.abspath(__file__)) 11 | 12 | def get_args(): 13 | parser = ArgumentParser() 14 | parser.add_argument("ncode", type=str, 15 | help="N-code") 16 | parser.add_argument("--reset", "-r", action="store_true", 17 | help="delete and refetch all parts") 18 | args = parser.parse_args() 19 | return args 20 | 21 | def main(): 22 | args = get_args() 23 | ncode = args.ncode 24 | resetFlag = args.reset 25 | 26 | # ncodeのバリデーションチェック 27 | ncode = ncode.lower() 28 | if not re.match(r"n[0-9]{4}[a-z]{2}", ncode): 29 | print("Incorrect N-code!!") 30 | sys.exit(1) 31 | 32 | # 全部分数を取得 33 | info_url = "https://ncode.syosetu.com/novelview/infotop/ncode/{}/".format(ncode) 34 | try: 35 | info_res = request.urlopen(info_url) 36 | except Exception: 37 | print("Incorrect N-code!!") 38 | sys.exit(1) 39 | soup = BeautifulSoup(info_res, "html.parser") 40 | pre_info = soup.select_one("#pre_info").text 41 | num_parts = int(re.search(r"全([0-9]+)部分", pre_info).group(1)) 42 | 43 | # 小説を保存するディレクトリがなければ作成 44 | novel_dir = os.path.normpath(os.path.join(dir_base, "{}".format(ncode))) 45 | if not os.path.exists(novel_dir): 46 | os.mkdir(novel_dir) 47 | 48 | # すでに保存している部分番号のsetを取得 49 | re_part = re.compile(r"{}_([0-9]+).txt".format(ncode)) 50 | existing_parts = {int(re_part.search(fn).group(1)) for fn in os.listdir(novel_dir)} 51 | 52 | # 新たに取得すべき部分番号のリストを生成 53 | # resetFlagがTrueならすべての部分を取得する 54 | if resetFlag: 55 | fetch_parts = list(range(1, num_parts+1)) 56 | else: 57 | fetch_parts = set(range(1,num_parts+1)) - existing_parts 58 | fetch_parts = sorted(fetch_parts) 59 | 60 | num_fetch_rest = len(fetch_parts) 61 | for part in fetch_parts: 62 | # 作品本文ページのURL 63 | url = "https://ncode.syosetu.com/{}/{:d}/".format(ncode, part) 64 | 65 | res = request.urlopen(url) 66 | soup = BeautifulSoup(res, "html.parser") 67 | 68 | # CSSセレクタで本文を指定 69 | honbun = soup.select_one("#novel_honbun").text 70 | honbun += "\n" # 次の部分との間は念のため改行しておく 71 | 72 | # 保存 73 | name = os.path.join(novel_dir, "{}_{:d}.txt".format(ncode, part)) 74 | with open(name, "w", encoding="utf-8") as f: 75 | f.write(honbun) 76 | 77 | # 進捗を表示 78 | num_fetch_rest = num_fetch_rest - 1 79 | print("part {:d} downloaded (rest: {:d} parts)".format( 80 | part, num_fetch_rest)) 81 | 82 | time.sleep(1) # 次の部分取得までは1秒間の時間を空ける 83 | 84 | 85 | if __name__ == "__main__": 86 | main() --------------------------------------------------------------------------------