문제 설명
크롤링하는 HTML 페이지에서 JavaScript 개체를 구문 분석하는 방법은 무엇입니까? (How to parse a JavaScript object from a HTML page I crawl?)
음식 레시피 페이지의 색인을 생성하려고 하는데 실제 레시피는 페이지의 JavaScript 내에 객체로 저장됩니다.
예제 URL: http://www.dagbladet.no/mat/oppskrift/bakt‑potet‑med‑romme ‑og‑blamuggostdressing
브라우저에서 개발자 도구를 열고 다음을 입력하면:
console.dir(food.recipeItem.title)
제목을 다시 얻습니다.
6"Bakt potet med rømme‑ og blåmuggostdressing"
전체 멋지고 멋지고 내가 필요한 것. 그러나 어떻게 그 스크립트를 파악하고 Node.js 애플리케이션 내에서 구문 분석할 수 있습니까? Cheerio가 대본을 찾는 데 도움이 될 수 있지만 그 이상은 하지 않습니까? 아니면 그럴까요? 어떻게 해야할지 모르겠지만, 가장 계산 효율적인 답변이 아닙니다. 또는 가장 견고합니다.
참조 솔루션
방법 1:
It's pretty easy, all you have to do is parse the returned HTML. If you inspect the returned HTML (view‑source:http://www.dagbladet.no/mat/oppskrift/bakt‑potet‑med‑romme‑og‑blamuggostdressing), you will find a script tag which contains all information you need in several javascript variables. These variables holds JSON data. Since the script is hardcoded directly into the HTML document, and not obtained by XHR or similar, parsing the HTML is the only way of doing this.
So basically you have these 3 steps:
1. send HTTP GET request to the link above
2. parse the HTML string to extract the script tag by using some library (check this link to decide which library to use).
3. parse the javascript string (extracted script from step 2) to extract JSON data. Check UglifyJS library for Node.js
(by Espen Klem、Boy)