LoginSignup
0
4

More than 3 years have passed since last update.

Pythonでリストアップされたhtmlの本文を抽出する。

Last updated at Posted at 2019-05-25

やったこと

htmlを記載したテキストファイルを読み込んで、
htmlの本文を抽出したファイルを出力する。

$ python python.py [input_file_name]
python.py
from readability.readability import Document
import urllib.request
# url encode
import urllib.parse
# markdown
import html2text
# datetime
import time
# 引数読み込み
import sys
from sys import argv

# htmlリストを読み込む
def get_page_list(input_file_path):
    page_list = []
    with open(input_file_path,'r') as f:
        for page in f:
                page_list.append(page)
        return page_list
# Webページから本文抽出
def read_page(page_list, output_file_path):
    with open(output_file_path, 'w', encoding = 'utf-8') as f:
        page_num = 1
        all_num = len(page_list)
        print("対象:" + str(all_num) + "件")
        error_num = 0;
        for page in page_list:
                print(page)
          # URLが読み込めない場合のエラー処理
                try:
                    url = urllib.request.urlopen(page)
                except:
                    print("読み込めませんでした。")
                    error_num += 1
                    continue
                source = url.read()
          #本文抽出
                article = Document(source).summary()
                text = html2text.html2text(article)
                f.write(str(page_num) + "---ページ区切り---\n")
                f.write(text)
                f.write("\n")
        # 処理結果
        print("対象:" + str(all_num) + "件")
        print("成功:" + str(all_num - error_num) + "件")
        print("失敗:" + str(error_num) + "件")

def gethtmls():

def main():
    #引数の取得
    input_file_path = sys.argv[1]
    #ファイル実行開始時刻を取得
    timestr = time.strftime('%Y%m%d-%H%M%S')
    #出力ファイル名の生成
    output_file_path = './' + timestr + '_result.txt'
    # htmlをリストに格納
    page_list = get_page_list(input_file_path)
    # 各htmlの読み込み
    read_page(page_list, output_file_path)

if __name__ == '__main__':
        main()

参考

python - Python3でwebスクレイピングしたいのですが存在するURLが開けません。 - スタック・オーバーフロー
Python - コマンドライン引数でファイル名を入力して、numpyで開きたい|teratail

0
4
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
0
4