LoginSignup
14
10

More than 5 years have passed since last update.

価格.comの性能比較ページをスクレイピングする

Last updated at Posted at 2018-03-22

価格.com - ノートパソコン スペック検索・性能比較
このページの情報をまるっと取得して、DataFrame化したい。

単純なテーブルの場合

import pandas as pd

dfs = pd.read_html('http://kakaku.com/specsearch/0020/')

でDataFrameのlistを簡単に取得できる。
が、このページの場合はtableタグの中にtableタグが使われていたりしてうまく取得できない。

Selenium + Beautiful Soupでスクレイピング

Seleniumでページ遷移しながら、Beautiful SoupでHTMLをパースして情報を取得していく。

import time

from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--headless')

driver_path = 'path/to/chromedriver.exe'

driver = webdriver.Chrome(executable_path=driver_path, chrome_options=options)

url = 'http://kakaku.com/specsearch/0020/'

product_list = []

while True:
    data = driver.page_source

    # HTMLをpythonのリストへ変換
    product_list = product_list + convert_list(data)

    # 次ページへのリンクをクリック
    driver.find_element_by_class_name('paging').find_elements_by_tag_name('a')[-1].find_element_by_tag_name('span').click()

    # 適切な待ち時間    
    time.sleep(1)

df = pd.DataFrame(product_list)
def convert_list(data):
    html = BeautifulSoup(data, 'lxml')

    # table部分の取得
    table = html.find_all('table', attrs={'class': 'tblBorderGray02'})[0]

    # 商品レコードのみを抽出
    # 商品レコード行はclassがない
    records = table.find_all('tr', class_=False)

    product_list = []
    for record in records:
        record_dict = {}
        try:
            record_dict['id'] = record.select('input[type=checkbox]')[0].attrs['value']
            record_dict['manufacturers'] = record.find('td', class_='textL').find('strong').text
            record_dict['product_name'] = record.find('td', class_='textL').find('a').text
            record_dict['screen_size'] = record.find('label', attrs={'title': '液晶サイズ'}).text
            # その他必要な情報を取得する

        except:
            # 本来は適切なエラー処理を書く
            break

        product_list.append(record_dict)

    return product_list
id manufacturers product_name screen_size ...
0 J0000025028 ASUS ASUS VivoBook E203NA E203NA-232 WXGA (1366x768) ...
1 K0000980972 FRONTIER FRT103(/KD) 2in1 PC 着脱式キーボード搭載/Win10 価格.com限定モデル WXGA (1280x800) ...
2 K0000829506 Acer Aspire One Cloudbook 11 AO1-131-F12N/KK WXGA (1366x768) ...

色々と粗はあるが、ひとまず目的は達成できた。
もしかしたらもっと簡単にできるかも……

14
10
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
14
10