还在用Python爬虫?教你一招,摆脱选择元素位置的烦恼!使用Node.js大杀器,并且无需使用cheerio 库~

发布时间 2024-01-07 02:43:21作者: 我的小叮当

咱们以豆瓣历史250最佳电影为例。

豆瓣说,>_< 你不要过来啊!

第一步:打开网页源代码

第二步:选择你想要爬虫的元素,右键复制获取JS路径

document.querySelector("#content > div > div.article > ol > li:nth-child(3) > div > div.pic > a > img")

第三步:将这个路径复制到代码

//引入模块
const https = require('https')
// 不使用cheerio完成爬虫
const cheerio = require('cheerio') 
const fs = require('fs')
const jsdom = require('jsdom')
const { JSDOM } = jsdom;
//获取页面的html结构
https.get('https://movie.douban.com/top250', function (res) {
    let html = ''
    res.on('data', function (chunk) {
        // console.log(chunk + '');
        html += chunk
    })

    res.on('end', function () {

        const dom = new JSDOM(html)

        var movieElement = dom.window.document.querySelector("#content > div > div.article > ol > li:nth-child(3) > div > div.pic > a > img")
        console.log(movieElement.src)
        
    })
})
// 打印内容 https://img3.doubanio.com/view/photo/s_ratio_poster/public/p2372307693.jpg

咱们这个代码很简单,没写过node.js的同学也很容易看懂。引入包,再执行一个http的get操作拿到整个页面的html。

可以看到咱们的代码并没有用cheerio这个库,而是直接将整个html变成一个dom对象,再对dom对象执行点点点的操作就可以得到我们想要的任意元素。

类似的网页我们都可以这么去爬取,再也不需要使用各种正则,遭遇找不到元素内容的烦恼啦!!!

上完全体代码(爬一页25个电影,并保存到本地文件)

//引入模块
const https = require('https')
// 不使用cheerio完成爬虫
const cheerio = require('cheerio') 
const fs = require('fs')
const jsdom = require('jsdom')
const { JSDOM } = jsdom;
//获取页面的html结构
https.get('https://movie.douban.com/top250', function (res) {
    let html = ''
    res.on('data', function (chunk) {
        // console.log(chunk + '');
        html += chunk
    })

    res.on('end', function () {

        const dom = new JSDOM(html)

        // 获取所有的电影元素
        var movieElements = dom.window.document.querySelectorAll("#content > div > div.article > ol > li")
    
        console.log(movieElements.length)
        let allFiles = []
        let id = 0
        movieElements.forEach(function(element) {
            // console.log(element.innerHTML)
            title = element.querySelector("div.item > div.info > div.hd > a > span.title:first-of-type").textContent
            pic = element.querySelector("div.item > div.pic > a > img").src
            star = element.querySelector("div.item > div.info > div.bd > div > span.rating_num").textContent
            console.log({
                id: id,
                title: title,
                pic: pic,
                star: star
            })
            allFiles.push({
                id: id,
                title: title,
                pic: pic,
                star: star 
            })
            id += 1
        });

        //将数据写入文件中
        fs.writeFile('./files.json', JSON.stringify(allFiles), function (err, data) {
            if (err) {
                throw err
            }
            console.log('文件保存成功');
        })
    })
})