LoginSignup
1
1

More than 3 years have passed since last update.

denoでもお手軽スクレイピング2020年夏

Posted at

お題

Node.js でお手軽スクレイピング 2020 年夏 - Qiitaをdenoでやってみたんだなも。
ぜひ読んでいってくださいだなも。

ちなみに当方は普段Pythonで、TypeScriptもnodeもJavaScriptも初心者だなも。

ソース

いきなりソースだなも。

test_scraping.ts
import jsdom from 'https://dev.jspm.io/jsdom'

const res = await fetch('https://www.jma.go.jp/jp/week/319.html')
const html = await res.text()
// console.log(html)

// jsdomでエラーが出るため、imgタグを削除
// error: Uncaught TypeError: Canvas.Image is not a constructor
//         this._image = new Canvas.Image();
const filt_html = html.replace(/<img.*?>/g, '')
// console.log(filt_html)

const dom = new jsdom.JSDOM(filt_html)
const document = dom.window.document
const nodes = document.querySelectorAll('#infotablefont tr:nth-child(4) td')

const tokyoWeathers = Array.from(nodes).map((td?:any) => td.textContent.trim())
console.log(tokyoWeathers)

実行結果

--allow-netを忘れずにだなも。

$ deno --version
deno 1.2.0
v8 8.5.216
typescript 3.9.2
$ deno run --allow-net test_scraping.ts
[
  "雨時々止む", "曇一時雨",
  "曇", "曇時々晴",
  "曇時々晴", "曇時々晴",
  "曇時々晴"
]

解説

ほぼ参照元と同じだなも。
はまったとこだけ書くのだなも。

  • jsdomライブラリのインポート
    ここで解決しだなも。
    jsdom Port for 1.0 (Feature Request) · Issue #3447 · denoland/deno
    jspm.ioはよくわからないけど、cdnだと思っておくだも。

  • jsdom Imageエラー
    jsdomでエラーが出たので、試行錯誤の末、imgタグを消すという荒業をやっただなも。
    (npm:jsdom@16.3.0)

  • any問題
    mapで、(td?:any) をつけないと推論で、怒られるんだなも。

終わりに

この情報は、本来なら40000ベルのところ、今だけ5000ベルだなも。ローンも組めるだなも。

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