3
2
記事投稿キャンペーン 「2024年!初アウトプットをしよう」

アスクルのサイトの購入履歴取得〜スクレイピング〜

Last updated at Posted at 2024-01-11

前回、アスクルの購入履歴をCSVに保存するため、まず該当ページのhtmlをローカルに保存するコードについて紹介しました。

今回は、保存したhtmlから情報をCSVに書き込むコードの投稿となります。

scraping.py

import os
from glob import glob

from bs4 import BeautifulSoup
import pandas as pd

#htmlファイルを読み込み、スクレイピングするため、まずhtmlファイルのあるディレクトリパスを取得する
html_path = os.path.join(os.path.dirname(
    os.path.abspath(__file__)), 'html', '*')

list = []

#htmlファイルをforループで回し、スクレイピングする
for path in glob(html_path):
    with open(path, 'r') as f:
        html = f.read()

    soup = BeautifulSoup(html, 'lxml')

    order_tags = soup.select('div.view2_order_history div.view2_record')

    for order_tag in order_tags:
        #注文日の取得
        order_day = order_tag.select_one('div.view2_record_head_box > p > span').text
        #合計価格の取得
        #total_price = order_tag.select_one('div.view2_tooltip_status_2 > p').text
        
        product_tags = order_tag.select('div.view2_record_detail')

        for product_tag in product_tags:
            name_tags = product_tag.select('h3 > a')
            #品名の取得
            for name_tag in name_tags:
                name = name_tag.text

            #価格の取得
            price = product_tag.select_one('td.money > span').text
            #数量の取得
            quantity_tags = product_tag.select('#qtyTd > span')
            for quantity_tag in quantity_tags:
                quantity = quantity_tag.text

            #小計の取得
            subtotal_tags = product_tag.select('#intaxSubttlAmntTd > span')
            for subtotal_tag in subtotal_tags:
                subtotal = subtotal_tag.text

            list.append({             
                '注文日': order_day,
                # '合計価格': total_price,
                '品名': name,
                '価格': price,
                '数量': quantity,
                '小計(税込)': subtotal,
                })  
            print(list[-1])

#作成した辞書をデータフレームにする
df = pd.DataFrame(list)
#重複する行を削除
new_df = df.drop_duplicates()
#注文日の列を降順でソート
df_sorted = new_df.sort_values('注文日', ascending=False)
#最後にCSV出力
df_sorted.to_csv('list.csv', index=False, encoding='utf-8-sig')

これで情報を取得できました。以下は、取得したCSVファイルのスクリーンショットです。
CSVファイル.png

参考サイト

3
2
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
3
2