💎 JavaScriptでスタティックウェブサイトをクロールする方法💥
16806 ワード
前提条件:JavaScriptについて少し知っている.
今日のトピックは、静的なウェブサイトからデータを抽出し、データベースやファイル、またはコンピュータ上のファイル、または何か全く別のデータを構築します.
フェッチクローラ(ノードJS )の紹介
分散クローリング 並列、再試行、最大要求、要求間の時間を設定します. サポートdepth-first search and breadth-first search アルゴリズム 要求の最大量が実行された後に停止する 挿入Cheerio 自動的にこする 約束 完全なドキュメントはgithubにあります.https://github.com/viclafouch/Fetch-Crawler
フェッチクローラの特異性は、並列に要求を管理する(例:同時に10個の要求ではなく、1つずつ)重要な時間節約を可能にする.
言い換えると、このライブラリはあなたのためにすべてを行います.
一歩一歩
今日のトピックは、静的なウェブサイトからデータを抽出し、データベースやファイル、またはコンピュータ上のファイル、または何か全く別のデータを構築します.
フェッチクローラ(ノードJS )の紹介
フェッチクローラーは、ウェブサイトをクロールするための基本的な、柔軟で堅牢なAPIを提供するように設計されています.
クローラは、次の機能を備えた静的なウェブサイトをクロールする単純なAPIを提供します
フェッチクローラの特異性は、並列に要求を管理する(例:同時に10個の要求ではなく、1つずつ)重要な時間節約を可能にする.
言い換えると、このライブラリはあなたのためにすべてを行います.
一歩一歩
まず、必要な依存関係をインストールします.
# npm i @viclafouch/fetch-crawler
次に、モジュールをJSファイルにインポートし、メソッドを使用しますlaunch
of FetchCrawler
. 必要な唯一のパラメータは、あなたのウェブサイト(またはページ)のリンクですhttps://github.com
.
const FetchCrawler = require('@viclafouch/fetch-crawler')
FetchCrawler.launch({
url: 'https://github.com'
})
を実行します.
# node example-crawl.js
このファイルをノードjsで実行すると動作しますが、クローラが終了するまでは何も起こらないでしょう.
では、ウェブサイトからデータを抽出するための基本的なオプションと方法に移りましょうdocumentation ):
const FetchCrawler = require('@viclafouch/fetch-crawler')
// `$ = Cheerio to get the content of the page
// See https://cheerio.js.org
const collectContent = $ =>
$('body')
.find('h1')
.text()
.trim()
// After getting content of the page, do what you want :)
// Accept async function
const doSomethingWith = (content, url) => console.log(`Here the title '${content}' from ${url}`)
// Here I start my crawler
// You can await for it if you want
FetchCrawler.launch({
url: 'https://github.com',
evaluatePage: $ => collectContent($),
onSuccess: ({ result, url }) => doSomethingWith(result, url),
onError: ({ error, url }) => console.log('Whouaa something wrong happened :('),
maxRequest: 20
})
さて、上記の新しい方法とオプションを見直しましょう.evaluatePage
: ページの内容を横断/操作する機能.チェリオマークアップを解析するために提供され、それを行うには、強力なAPIを提供します.それを使用すると、Webページから必要なデータの正確な部分を抽出するために特殊な機能を構築することができます.onSuccess
: If evaluatePage
成功すると、あなたは何をしたいですか?データベースにデータを追加します.onError
: ifというコールバックevaluatePage
が失敗する.maxRequest
: それはあなたのクローラを実行できるように要求の最大量を表します.パス-1
制限を無効にする.しかし、上記の例では、20リクエスト(失敗したとしても)後のクローラを停止したい.
残りの設定については、documentation はい.
例について
テレビゲームウェブサイトの例をしましょう:インスタントゲーム
私たちの目的:ビデオゲーム(Xbox上で)からのデータを回復し、ウェブサイト上で販売し、JSONファイルをコンパイルします.その後、プロジェクトで再利用することができます.
これが私たちのファイルですexample-crawl.js
が含まれます.
const fs = require('fs')
const FetchCrawler = require('@viclafouch/fetch-crawler')
// Get all games on xbox platform
const urlToCrawl = 'https://www.instant-gaming.com/en/search/?type%5B0%5D=xbox'
let games = []
// I'm getting an array of each game on the page (name, price, cover, discount)
const collectContent = $ => {
const content = []
$('.item.mainshadow').each(function(i, elem) {
content.push({
name: $(this)
.find($('.name'))
.text()
.trim(),
price: $(this)
.find($('.price'))
.text()
.trim(),
discount: $(this)
.find($('.discount'))
.text()
.trim(),
cover: $(this)
.find($('.picture'))
.attr('src')
})
})
return content
}
// Only url including an exact string
const checkUrl = url => {
try {
const link = new URL(url)
if (link.searchParams.get('type[0]') === 'xbox' && link.searchParams.get('page')) {
return url
}
return false
} catch (error) {
return false
}
}
// Concat my new games to my array
const doSomethingWith = content => (games = games.concat(content))
// Await for the crawler, and then save result in a JSON file
;(async () => {
try {
await FetchCrawler.launch({
url: urlToCrawl,
evaluatePage: $ => collectContent($),
onSuccess: ({ result, url }) => doSomethingWith(result, url),
preRequest: url => checkUrl(url),
maxDepth: 4,
parallel: 6
})
const jsonResult = JSON.stringify({ ...games }, null, 2)
await fs.promises.writeFile('examples/example_4.json', jsonResult)
} catch (error) {
console.error(error)
}
})()
我々が今しなければならないすべては、我々のクローラを始めて、数秒を待ちます.
# node example-crawl.js
JSONファイルを取得します.https://github.com/viclafouch/Fetch-Crawler/blob/master/examples/example_4.json
ご覧のように、JSONファイルにスーパークリーンデータを取得します.明らかに、ウェブサイトのデータはすぐに変わるので、我々はちょうど24時間ごとに我々のクローラをループさせることができました.
フェッチクローラパッケージの詳細については、チェックアウトしてくださいdocumentation .
...
読書ありがとう.
このパッケージで私に貢献してください.
私はGoogle用のプロジェクトのためにそれを必要とし、データの抽出はかなり困難だったので、このパッケージを構築しました.
Reference
この問題について(💎 JavaScriptでスタティックウェブサイトをクロールする方法💥), 我々は、より多くの情報をここで見つけました
https://dev.to/viclafouch/how-to-crawl-a-static-website-in-javascript-in-4min-36g3
テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol
# npm i @viclafouch/fetch-crawler
const FetchCrawler = require('@viclafouch/fetch-crawler')
FetchCrawler.launch({
url: 'https://github.com'
})
# node example-crawl.js
const FetchCrawler = require('@viclafouch/fetch-crawler')
// `$ = Cheerio to get the content of the page
// See https://cheerio.js.org
const collectContent = $ =>
$('body')
.find('h1')
.text()
.trim()
// After getting content of the page, do what you want :)
// Accept async function
const doSomethingWith = (content, url) => console.log(`Here the title '${content}' from ${url}`)
// Here I start my crawler
// You can await for it if you want
FetchCrawler.launch({
url: 'https://github.com',
evaluatePage: $ => collectContent($),
onSuccess: ({ result, url }) => doSomethingWith(result, url),
onError: ({ error, url }) => console.log('Whouaa something wrong happened :('),
maxRequest: 20
})
テレビゲームウェブサイトの例をしましょう:インスタントゲーム
私たちの目的:ビデオゲーム(Xbox上で)からのデータを回復し、ウェブサイト上で販売し、JSONファイルをコンパイルします.その後、プロジェクトで再利用することができます.
これが私たちのファイルです
example-crawl.js
が含まれます.const fs = require('fs')
const FetchCrawler = require('@viclafouch/fetch-crawler')
// Get all games on xbox platform
const urlToCrawl = 'https://www.instant-gaming.com/en/search/?type%5B0%5D=xbox'
let games = []
// I'm getting an array of each game on the page (name, price, cover, discount)
const collectContent = $ => {
const content = []
$('.item.mainshadow').each(function(i, elem) {
content.push({
name: $(this)
.find($('.name'))
.text()
.trim(),
price: $(this)
.find($('.price'))
.text()
.trim(),
discount: $(this)
.find($('.discount'))
.text()
.trim(),
cover: $(this)
.find($('.picture'))
.attr('src')
})
})
return content
}
// Only url including an exact string
const checkUrl = url => {
try {
const link = new URL(url)
if (link.searchParams.get('type[0]') === 'xbox' && link.searchParams.get('page')) {
return url
}
return false
} catch (error) {
return false
}
}
// Concat my new games to my array
const doSomethingWith = content => (games = games.concat(content))
// Await for the crawler, and then save result in a JSON file
;(async () => {
try {
await FetchCrawler.launch({
url: urlToCrawl,
evaluatePage: $ => collectContent($),
onSuccess: ({ result, url }) => doSomethingWith(result, url),
preRequest: url => checkUrl(url),
maxDepth: 4,
parallel: 6
})
const jsonResult = JSON.stringify({ ...games }, null, 2)
await fs.promises.writeFile('examples/example_4.json', jsonResult)
} catch (error) {
console.error(error)
}
})()
我々が今しなければならないすべては、我々のクローラを始めて、数秒を待ちます.# node example-crawl.js
JSONファイルを取得します.https://github.com/viclafouch/Fetch-Crawler/blob/master/examples/example_4.json ご覧のように、JSONファイルにスーパークリーンデータを取得します.明らかに、ウェブサイトのデータはすぐに変わるので、我々はちょうど24時間ごとに我々のクローラをループさせることができました.
フェッチクローラパッケージの詳細については、チェックアウトしてくださいdocumentation .
...
読書ありがとう.
このパッケージで私に貢献してください.
私はGoogle用のプロジェクトのためにそれを必要とし、データの抽出はかなり困難だったので、このパッケージを構築しました.
Reference
この問題について(💎 JavaScriptでスタティックウェブサイトをクロールする方法💥), 我々は、より多くの情報をここで見つけました https://dev.to/viclafouch/how-to-crawl-a-static-website-in-javascript-in-4min-36g3テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol