LoginSignup
1
0

More than 1 year has passed since last update.

pixivの小説作品のURLからテキストを保存する

Last updated at Posted at 2022-01-31

どうして作ったの?

※あくまでブラウザ内で確認するのが難しいテキスト情報を手元で確認するためのツールとしての利用を想定しています

TRPGの一つ、CoC(コールオブクトゥルフ)を最近頻繁にプレイしていてページ内だけで確認するのが手間だな・・・と思ったので作りました
pixivで一般公開されている名作のシナリオのテキスト量は膨大で、数十ページにおよぶためpixivサイト内だけで情報を確認することは難しい!
ということでpixivの小説作品のURLから本文のテキストだけを抽出するコードを作ってみました

環境

  • Google Colab

ざっくりやってること

  • seleniumを使って仮想ウェブブラウザを構築
  • html内のタグ情報を使って本文のテキストを取得
  • ページ遷移をさせつつ、リダイレクト後に同じページに飛ばされたらwhile文をbreakしてファイルを出力する

ソース

Colabへの環境構築

!pip install selenium
!apt-get update
!apt install chromium-chromedriver
!cp /usr/lib/chromium-browser/chromedriver /usr/bin

ライブラリの読み込みと環境設定

import urllib.request
from bs4 import BeautifulSoup
import time
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

関数

def main(url):
  lists = []
  idx = 1
  while True:
    browser = webdriver.Chrome('chromedriver',options=options)
    search_url = f'{url}#{str(idx)}'
    res = browser.get(search_url)
    time.sleep(1)
    current_url = browser.current_url
    print(idx)
    print(search_url)
    print(current_url)
    # リダイレクトが発生した際に同じURLに転送された場合処理を終了する
    if search_url != current_url:
      if idx == 1:
        pass
      else:
        break
    source = browser.page_source.replace("<br>", "\n") # レイアウト上の改行要素を事前にテキスト用に変換しておく
    soup = BeautifulSoup(source, 'html.parser')
    sentences = soup.find_all('p', attrs={'class': 'sc-dIvrsQ leiCDy'})
    for sentence in sentences:
        # 文字部分のみを抽出する
        sentence = sentence.get_text().replace("\r", "").replace("\u3000", "")
        lists.append(sentence)
    idx += 1
  lists = '\n'.join(lists)
  return lists

呼び出し例

url = 'https://www.pixiv.net/novel/show.php?id=16394819'
lists = main(url)
print(lists)
  • このあとは好きにテキストファイルに保存するなりコピペするなりできます

終わりに

良きCoCライフを!!!

個人的にリダイレクトを待つコードの位置を間違えてリダイレクト前のURLを一生参照していたのが最初は何故か分かりませんでしたが気づいてしまったら綺麗に動いてくれて一安心
一応pixiv小説とかにも汎用性があるコードになっているはずですが、pixivさんのサイト仕様の変更に伴って利用できなくなると思うのでニーズがあれば更新いたします

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0