第5章 クローリング・スクレイピングの実践とデータの活用
JavaScript が使われているページのスクレイピングを行います。
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()
本
![Pythonクローリング&スクレイピング[増補改訂版] -データ収集・解析のための実践開発ガイド Pythonクローリング&スクレイピング[増補改訂版] -データ収集・解析のための実践開発ガイド](https://images-fe.ssl-images-amazon.com/images/I/41VimzqqXAL._SL160_.jpg)
Pythonクローリング&スクレイピング[増補改訂版] -データ収集・解析のための実践開発ガイド
- 作者: 加藤耕太
- 出版社/メーカー: 技術評論社
- 発売日: 2019/08/10
- メディア: 単行本(ソフトカバー)
- この商品を含むブログを見る
感想
ちょっとクローリングに飽きてきたので、何か目的をもってプログラミングを学習していきたいですね。