ヤマカサのプログラミング勉強日記

プログラミングに関する日記とどうでもよい雑記からなるブログです。

Pythonクローリング&スクレイピング[増補改訂版] ―データ収集・解析のための実践開発ガイドー その15

第5章 クローリング・スクレイピングの実践とデータの活用

JavaScript が使われているページのスクレイピングを行います。

note のスクレイピング

note というと有料で記事を販売できるということしか知りませんが、おすすめされる記事の取得を行います。

note ――つくる、つながる、とどける。

note では、画面を下にスクロールすると新しい記事が読み込まれる構造になっています。

import logging
import time
from typing import List

from selenium.webdriver import Chrome, ChromeOptions, Remote
from selenium.common.exceptions import NoSuchElementException


def main():
    
    options = ChromeOptions()
    options.headless = True
    driver = Chrome(options=options)
    print('AAAAA')
    navigate(driver)
    
    contents = scrape_contents(driver)
    
    logging.info(f'Found {len(contents)} contents.')

    for content in contents:
        print(content)
    
    driver.quit()


def navigate(driver: Remote):
    logging.info('Navigating...')
    driver.get('https://note.mu/')
    assert 'note' in driver.title

    # _ は変数を利用しないということ
    for _ in range(3):
        driver.execute_script('scroll(0, document.body.scrollHeight)')
        logging.info('Waiting for contents to be loaded...')
        time.sleep(1)


def scrape_contents(driver: Remote) -> List[dict]:
    contents = []
    
    for div in driver.find_elements_by_css_selector('.o-timeline__item'):
       
        a = div.find_element_by_css_selector('a')
        try:
            descriptioin = div.find_element_by_css_selector('p').text
        except NoSuchElementException:
            descriptioin = '' # p要素がない場合は空文字
        
        contents.append({
            'url': a.get_attribute('href'),
            'title': div.find_element_by_css_selector('h3').text,
            'description': descriptioin,
            'like': int(div.find_element_by_css_selector('.o-noteStatus__item--like .o-noteStatus__label').text),
        })
    
    return contents


if __name__=='__main__':
    logging.basicConfig(level=logging.INFO)
    
    main()

感想

ちょっとクローリングに飽きてきたので、何か目的をもってプログラミングを学習していきたいですね。