自适应网站模板源码,网站风格,有名的seo外包公司,前端电视剧写一个关于图片爬取的小案例
爬取效果 使用插件如下#xff1a;
{dependencies: {axios: ^1.6.0,cheerio: ^1.0.0-rc.12,request: ^2.88.2}
}新建一个config.js配置文件
// 爬取图片…写一个关于图片爬取的小案例
爬取效果 使用插件如下
{dependencies: {axios: ^1.6.0,cheerio: ^1.0.0-rc.12,request: ^2.88.2}
}新建一个config.js配置文件
// 爬取图片网站
const url http://m.hydcd.com/cy/fkccy/index9.htm//可以自行修改网址
// http://www.hydcd.com/cy/fkccy/index.htm
// http://m.hydcd.com/cy/fkccy/
const path require(path);
//图片下载文件夹
const imgDir path.join(__dirname, img)module.exports.url url
module.exports.imgDir imgDir 找到需要下载的文件原元素位置
const cheerio require(cheerio)function findImg(dom, callback) {let $ cheerio.load(dom,{decodeEntities: false});//找到图片的位置 并获取图片链接$(table tbody tr td img).each(function (i, elem) {let imgSrc $(this).attr(src);let alt $(this).attr(alt);callback(imgSrc, i,alt)})
}
module.exports.findImg findImg; const request require(request)
const path require(path)
const config require(./config)
const analyze require(./analyze)
const fs require(fs)function start() {request(config.url, function (err, res, body) {console.log(start);if (!err res) {console.log(start);analyze.findImg(body, download,{decodeEntities: false});}})
}
//这个图片地址链接前缀
let imgUrlPath http://m.hydcd.com/cy/fkccy/
function download(imgUrl, i,alt) {console.log(imgUrl,11111)let txt imgUrl.split(images/)[1];request(imgUrlPathimgUrl).pipe(fs.createWriteStream(path.join(config.imgDir, txt), {encoding: UTF-8,}))
}start();以下是一个使用 Node.js 和 Cheerio 爬取网站图片的示例代码
const axios require(axios);
const cheerio require(cheerio);
const fs require(fs);// 定义要爬取的网页 URL
const url https://example.com;// 发起 GET 请求获取网页内容
axios.get(url).then(response {// 使用 Cheerio 加载网页内容const $ cheerio.load(response.data);// 定义一个数组来保存图片 URLconst imageUrls [];// 遍历页面中的图片标签$(img).each((index, element) {// 获取图片的 src 属性值const imageUrl $(element).attr(src);// 将图片的 URL 添加到数组中imageUrls.push(imageUrl);});// 下载图片imageUrls.forEach((imageUrl, index) {// 发起 GET 请求获取图片内容axios.get(imageUrl, { responseType: stream }).then(response {// 创建一个可写流将图片内容写入到文件中const writeStream fs.createWriteStream(image${index1}.jpg);// 将响应的数据流导向可写流response.data.pipe(writeStream);}).catch(error {console.error(下载图片失败${error});});});}).catch(error {console.error(获取网页内容失败${error});});
请注意上述示例中的 https://example.com 是一个示例网站的 URL你需要替换为你要爬取图片的实际网站 URL。
这段代码首先使用 Axios 发起 GET 请求获取网页内容然后使用 Cheerio 加载网页内容对图片标签进行遍历获取图片的 src 属性值并保存到一个数组中。最后通过循环遍历数组中的图片 URL使用 Axios 再次发起 GET 请求获取图片内容并通过可写流将图片内容写入到文件中。你可以自定义文件名和保存路径。
请注意进行网站爬取时一定要遵守法律法规并注意对网站的使用限制和版权保护。同时不要对不允许爬取的网站进行爬取以免触犯相关法律法规并造成不良后果!!!!