咱们以豆瓣历史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('文件保存成功');
})
})
})
以上就是“还在用Python爬虫?教你一招,摆脱选择元素位置的烦恼!使用Node.js大杀器,并且无需使用cheerio 库~”的全部内容,希望对你有所帮助。
关于Python技术储备
学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!
一、Python所有方向的学习路线
Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
二、Python必备开发工具
三、Python视频合集
观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
四、实战案例
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。
五、Python练习题
检查学习结果。
六、面试资料
我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
最后祝大家天天进步!!
上面这份完整版的Python全套学习资料已经上传至CSDN官方,朋友如果需要可以直接微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】。