2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

puppeteer触ってみた

Last updated at Posted at 2018-10-20

puppeteerとは

Googleが開発している、NodeJSからHeadless Chrome(GUIなし)を操作できるフレームワーク。
主にスクレイピングやSPAの自動テストに用いられることが多い。

puppeteerのインストール

npm install puppeteer

スクレイピングしてみる

puppeteerでスクレイピング

実際にフォームにパスワードを入力して認証を通してみる例。
公式ではasync/awaitを使ったコードが例示されているので敢えてPromise使ってみます。


const puppeteer = require('puppeteer');

puppeteer.launch({
    //# WindowsではHeadlessモードでTimeoutしてしまう問題があるのでfalse
    headless: false, 
})
.then((browser)=>{
    browser.newPage()
    .then((page)=>{
        //ページ遷移
        page.goto('https://www.freeml.com/kimetaro/******')
        .then(resp=>{
            //フォーム入力
            page.type(
                'input[name="view_password"]',
                'xxxx')
            .then(
                //ボタンクリック
                setTimeout(()=>{
                    page.click('.ok_btn')
                },1000)
                
            )
        })
        .catch(err=>console.log(err))
    })
})

要素を取得してみるコード
puppeteerでの要素の取得方法

const puppeteer = require('puppeteer');

puppeteer.launch({
    headless: false
})
.then((browser)=>{
        browser.newPage()
        .then((page)=>{
            let i=471652
            let req4=i.toString().substring(0,4)
            let req2=i.toString().substring(4,6)
            console.log(req4+'-'+req2)
            page.goto('http://www.clubdam.com/app/damStation/clubdamRanking.do?requestNo='+req4+'-'+req2)
            .then(resp=>{
                              
                page.evaluate(()=>{
                    console.log(document)
                    var title=document.querySelector('div #Rankingbattle tbody tr td a').textContent
                    var artist= document.querySelectorAll('div #Rankingbattle table.list_rankingbattle_title tr td')
                    return {
                        title:title,
                        //ページコンテンツがない場合は落ちるので事前にnull確認が必要
                        artist:artist[3].textContent
                    }
                })
                .then((result)=>{
                    console.log(result)
                })
                
            })
            .catch(err=>console.log(err))
        })
})



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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?