キジ(@kiji) です。今回はPuppeteerで入力フォームに入力して、検索することをやりたいと思います。
前回の記事はこちらです。
本記事でできること
今回もYahooファイナンスを利用します。
検索ボックスに、銘柄コードを入力して、隣りにある株価検索を押下して、画面遷移先の情報を取得させます。

環境
$ node -v
v14.17.3
# typescript
4.4.2
# puppeteer
10.2.0
説明
Puppeteerでは、「type」というメソッドが用意されています。
typeは、セレクタを指定して任意の文字列を入力することができます。
page.type("セレクタ", "入力文字列");
ソースコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Browser, Page } from "puppeteer"; | |
const puppeteer = require('puppeteer'); | |
const target_url = "https://info.finance.yahoo.co.jp/ranking/?kd=8&mk=1&tm=d&vl=a"; | |
const sleep = async ( time : number ) => { await setTimeout(() => {}, time);} | |
( async () => { | |
// browserを立ち上げる | |
let browser; | |
// page(tab)を生成する | |
let page; | |
try { | |
browser = await puppeteer.launch({ | |
'headless' : false, | |
'slowMo' : 100, | |
'args': [ `–window-size=1200,800` ], | |
'defaultViewport': { | |
'width':1200, | |
'height':800 | |
} | |
}) as Browser; | |
browser | |
page = await browser.newPage() as Page; | |
// 特定のURLへ移動する。 | |
// ページ読み込みができるまで待つ | |
await Promise.all([ | |
page.waitForNavigation({ 'waitUntil' : 'domcontentloaded', 'timeout' : 30000 }), | |
page.goto(target_url) | |
]); | |
// 遷移先のページ確認 | |
let dom = await page.content(); | |
if( dom.indexOf("rankingTableWrapper") < 0 ) { | |
throw new Error( "ページ遷移 失敗" ); | |
} | |
// 入力フォームの取得 | |
await page.type("#searchText", "7203"); | |
// 検索ボタンの押下 | |
const search_btn = await page.$("#searchButton"); | |
await Promise.all([ | |
page.waitForNavigation({ 'waitUntil' : 'networkidle0', 'timeout' : 30000 }), | |
search_btn?.click() | |
]); | |
} catch( e ) { | |
console.error( e ); | |
} finally { | |
// browserを閉じる | |
if( browser ) { | |
await browser.close(); | |
browser = undefined; | |
} | |
} | |
})( ); |
実行結果
まとめ
- Puppeteerをつかって、入力フォームに値を入力
- 検索フォームに入力して、検索ボタンの押下、画面繊維
今回の操作を用いれば、ログインの自動化をして任意の情報を取得することもできます。
コメント