当前位置: 首页 > news >正文

网站开发商城百度推广授权代理商

网站开发商城,百度推广授权代理商,株洲市政府门户网站,中国站长之家域名查询之前用python写过爬虫,这次想试试nodeJS爬虫爬取贴吧图片,话不多说代码如下,爬取制定吧的前十页所有帖子里的图片 爬取贴吧图片脚本 你得提前创建一个images文件夹 const axios require("axios"); const cheerio require("…

之前用python写过爬虫,这次想试试nodeJS爬虫爬取贴吧图片,话不多说代码如下,爬取制定吧的前十页所有帖子里的图片

 爬取贴吧图片脚本

你得提前创建一个images文件夹

const axios = require("axios");
const cheerio = require("cheerio");
const sanitize = require("sanitize-filename");
const fs = require("fs");
const path = require("path");// 定义要爬取的贴吧URL
const baseUrl = "https://tieba.baidu.com/f?kw=%CB%EF%D0%A6%B4%A8&fr=ala0&tpl=5&dyTabStr=MCwxLDMsMiw2LDQsNSw4LDcsOQ%3D%3D";// 发送HTTP请求获取页面内容
async function getTitlesByPage(pageNum) {const url = baseUrl + pageNum * 50;try {const response = await axios.get(url);if (response.status === 200) {// 使用cheerio解析页面const $ = cheerio.load(response.data);$(".threadlist_title a.j_th_tit").each((index, element) => {// 定义要下载的帖子URLconst url = "https://jump2.bdimg.com" + $(element).attr("href");// 发送HTTP请求获取页面内容axios.get(url).then((response) => {if (response.status === 200) {// 使用cheerio解析页面const $ = cheerio.load(response.data);// 获取帖子中的所有图片链接const imgUrls = [];$("img.BDE_Image").each((index, element) => {imgUrls.push($(element).attr("src"));});// 下载所有图片imgUrls.forEach((imgUrl, index) => {axios({method: "get",url: imgUrl,responseType: "stream",headers: {Referer: url,},}).then((response) => {const filename = sanitize(path.basename(imgUrl));const filePath = path.resolve(__dirname,`./images/${filename}.jpg`);response.data.pipe(fs.createWriteStream(filePath));console.log(`第 ${index + 1} 张图片下载完成`);}).catch((error) => {console.log(`第 ${index + 1} 张图片下载失败`, error);});});} else {console.log("请求失败");}}).catch((error) => {console.log("请求出错", error);});});} else {console.log(`请求第 ${pageNum + 1} 页失败`);}} catch (error) {console.log(`请求第 ${pageNum + 1} 页出错`, error);}
}async function getTitles() {for (let i = 0; i < 10; i++) {await getTitlesByPage(i);}
}getTitles();

这里有个弊端,IP会被马上封掉,那么通过爬取免费代理IP网站的IP去创建本地代理IP池txt文件

找了一个勉强可用的免费代理IP网站免费代理IP_免费HTTP代理IP_SOCKS5代理服务器_优质IP代理_89免费代理IP

里面的有效IP很少,那么得自己去大量爬取筛选可用IP

 这个是

爬取建立免费代理IP池的脚本

你得提前创建一个proxy.txt文件

const fs = require('fs');
const axios = require('axios');
const cheerio = require('cheerio');const headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36',
};async function get89IP(filePath) {for (let i = 1; i <= 10; i++) { // 循环采集前10页的数据const url = `https://www.89ip.cn/index_${i}.html`;try {const response = await axios.get(url, { headers });const $ = cheerio.load(response.data);const trs = $('table tbody tr');trs.each((index, element) => {const ip = $(element).find('td:nth-child(1)').text().trim();const port = $(element).find('td:nth-child(2)').text().trim();const proxyIP = `${ip}:${port}`;fs.appendFileSync(filePath, proxyIP + '\n');});console.log(`第${i}页采集完成`);} catch (error) {console.error('出错了:', error);}await new Promise((resolve) => setTimeout(resolve, 1000));}
}async function main() {const filePath = './proxy.txt';while (true) {try {await get89IP(filePath);console.log('采集完成');} catch (error) {console.error('出错了:', error);}await new Promise((resolve) => setTimeout(resolve, 60000));}
}main();

 采集完成后的筛选IP代码

 一个一个筛选太慢,这里使用到了Promise.all

你得提前创建一个KyProxy.txt文件

const fs = require('fs');
const axios = require('axios');const proxyList = fs.readFileSync('proxy.txt', 'utf-8').split('\n').filter(Boolean);async function testProxy(ip) {try {const response = await axios.get('https://tieba.baidu.com/', {proxy: {host: ip.split(':')[0],port: ip.split(':')[1]},timeout: 5000});if (response.status === 200 || response.status === 302) {return true;}} catch (error) {console.error(error);}return false;
}async function main() {const promiseArr = [];for (const proxy of proxyList) {promiseArr.push(testProxy(proxy));}const resultArr = await Promise.all(promiseArr);const validProxies = resultArr.reduce((acc, curr, index) => {if (curr) {acc.push(proxyList[index]);console.log(`代理IP ${proxyList[index]} 可用`);} else {console.log(`代理IP ${proxyList[index]} 不可用`);}return acc;}, []);fs.writeFileSync('kyProxy.txt', validProxies.join('\n'));console.log('可用代理IP已写入 kyProxy.txt');
}main().catch((error) => console.error(error));

 到这一步kyProxy.txt里面的IP基本是稳定可用的了,最后一步就是使用kyProxy.txt里的代理I去爬取图片

 通过代理IP爬取贴吧图片

const axios = require("axios");
const cheerio = require("cheerio");
const sanitize = require("sanitize-filename");
const fs = require("fs");
const path = require("path");// 定义要爬取的贴吧URL
const baseUrl ="https://tieba.baidu.com/f?kw=%CB%EF%D0%A6%B4%A8&fr=ala0&tpl=5&dyTabStr=MCwxLDMsMiw2LDQsNSw4LDcsOQ%3D%3D";// 获取代理IP池
async function getProxyList() {const fileContent = await fs.promises.readFile(path.resolve(__dirname, "./kyProxy.txt"),"utf8");return fileContent.trim().split("\n");
}// 发送HTTP请求获取页面内容
async function getTitlesByPage(pageNum, proxyList) {const url = baseUrl + pageNum * 50;try {let success = false;for (let i = 0; i < proxyList.length; i++) {const proxy = `${proxyList[i]}`;console.log(`使用代理IP:${proxy}`);try {const response = await axios.get(url, {proxy: {host: proxyList[i].split(":")[0],port: proxyList[i].split(":")[1],},});if (response.status === 200) {// 使用cheerio解析页面const $ = cheerio.load(response.data);$(".threadlist_title a.j_th_tit").each(async (index, element) => {// 定义要下载的帖子URLconst url = "https://jump2.bdimg.com" + $(element).attr("href");// 发送HTTP请求获取页面内容const imgUrls = await getImgUrls(url, proxy);// 下载所有图片for (let j = 0; j < imgUrls.length; j++) {await downloadImg(imgUrls[j], j, url, proxy);}});success = true;break;} else {console.log(`代理IP ${proxy} 请求失败`);}} catch (error) {console.log(`代理IP ${proxy} 请求出错`, error);}}if (!success) {console.log(`请求第 ${pageNum + 1} 页失败,跳过`);}} catch (error) {console.log(`请求第 ${pageNum + 1} 页出错`, error);}
}// 获取帖子中的所有图片链接
async function getImgUrls(url, proxy) {try {const response = await axios.get(url, {proxy: {host: proxy.split(":")[0],port: proxy.split(":")[1],},headers: {Referer: url,},});if (response.status === 200) {const $ = cheerio.load(response.data);const imgUrls = [];$("img.BDE_Image").each((index, element) => {imgUrls.push($(element).attr("src"));});return imgUrls;} else {console.log(`请求 ${url} 失败`);return [];}} catch (error) {console.log(`请求 ${url} 出错`, error);return [];}
}// 下载单张图片
async function downloadImg(imgUrl, index, url, proxy) {try {const response = await axios({method: "get",url: imgUrl,responseType: "stream",proxy: {host: proxy.split(":")[0],port: proxy.split(":")[1],},headers: {Referer: url,},});if (response.status === 200) {const filename = sanitize(path.basename(imgUrl));const filePath = path.resolve(__dirname, `./images/${filename}.jpg`);response.data.pipe(fs.createWriteStream(filePath));console.log(`第 ${index + 1} 张图片下载完成`);} else {console.log(`第 ${index + 1} 张图片下载失败`);}} catch (error) {console.log(`第 ${index + 1} 张图片下载出错`, error);}
}async function getTitles() {const proxyList = await getProxyList();for (let i = 0; i < 10; i++) {await getTitlesByPage(i, proxyList);}
}getTitles();

爬取效果

效果还可以


文章转载自:
http://dichromatism.c7501.cn
http://lithography.c7501.cn
http://eau.c7501.cn
http://sestertii.c7501.cn
http://gomorrah.c7501.cn
http://inapplicable.c7501.cn
http://footlocker.c7501.cn
http://proponent.c7501.cn
http://dct.c7501.cn
http://numskull.c7501.cn
http://expansionist.c7501.cn
http://milkman.c7501.cn
http://soapbox.c7501.cn
http://sagamore.c7501.cn
http://evaginable.c7501.cn
http://tricerium.c7501.cn
http://bosie.c7501.cn
http://cancer.c7501.cn
http://virustatic.c7501.cn
http://listless.c7501.cn
http://immunocyte.c7501.cn
http://flexagon.c7501.cn
http://alissa.c7501.cn
http://ophthalmia.c7501.cn
http://cosmochemistry.c7501.cn
http://twill.c7501.cn
http://vauntingly.c7501.cn
http://module.c7501.cn
http://necessitous.c7501.cn
http://smaze.c7501.cn
http://serology.c7501.cn
http://enervate.c7501.cn
http://dollface.c7501.cn
http://phrenetic.c7501.cn
http://crystallize.c7501.cn
http://napped.c7501.cn
http://hashbury.c7501.cn
http://calamity.c7501.cn
http://scuncheon.c7501.cn
http://geognostic.c7501.cn
http://letterspacing.c7501.cn
http://trophic.c7501.cn
http://backslash.c7501.cn
http://modernism.c7501.cn
http://ebullience.c7501.cn
http://ppcc.c7501.cn
http://pix.c7501.cn
http://microphotometer.c7501.cn
http://inconsistently.c7501.cn
http://jedediah.c7501.cn
http://nighttime.c7501.cn
http://pediform.c7501.cn
http://sophisticate.c7501.cn
http://hemogram.c7501.cn
http://subtilize.c7501.cn
http://fluxion.c7501.cn
http://ruinously.c7501.cn
http://paleethnology.c7501.cn
http://salomonian.c7501.cn
http://evildoing.c7501.cn
http://fusionism.c7501.cn
http://demarcative.c7501.cn
http://reemerge.c7501.cn
http://ashtray.c7501.cn
http://programing.c7501.cn
http://caste.c7501.cn
http://galvanotropic.c7501.cn
http://vindicator.c7501.cn
http://downslope.c7501.cn
http://auklet.c7501.cn
http://qom.c7501.cn
http://edaphon.c7501.cn
http://pilliwinks.c7501.cn
http://awing.c7501.cn
http://reforestation.c7501.cn
http://whack.c7501.cn
http://peloponnesus.c7501.cn
http://rightness.c7501.cn
http://thermion.c7501.cn
http://angelic.c7501.cn
http://carbuncled.c7501.cn
http://zygosperm.c7501.cn
http://stuff.c7501.cn
http://hhd.c7501.cn
http://equiangular.c7501.cn
http://ornithology.c7501.cn
http://fishery.c7501.cn
http://hypsometrical.c7501.cn
http://dpi.c7501.cn
http://malta.c7501.cn
http://podzolize.c7501.cn
http://encyclopedia.c7501.cn
http://heilung.c7501.cn
http://compressional.c7501.cn
http://lardy.c7501.cn
http://latewood.c7501.cn
http://bootie.c7501.cn
http://retrogression.c7501.cn
http://swipes.c7501.cn
http://impendence.c7501.cn
http://www.zhongyajixie.com/news/79208.html

相关文章:

  • 同ip网站seo完整教程视频教程
  • b2c网站开发百度账号人工客服
  • wordpress勾子合肥网站优化搜索
  • 网站设计的思想市场调研报告800字
  • 网站后台功能开发必应搜索引擎下载
  • 互联网保险下架优化设计卷子答案
  • 重庆怎么在网站上做广告免费建立一个网站
  • 惠州网站制作培训东莞seo网络公司
  • 广西建设职业技术学院图书馆网站电商培训有用吗
  • wordpress 文章字体seo关键词分类
  • 58加盟创业网郑州关键词优化费用
  • 南京政府网站建设好看的web网页
  • 企业网站名称怎么写培训班报名
  • 题库网站建设的绩效指标东莞seo建站
  • 营销型网站及原因有哪些方面广州最新疫情最新消息
  • 南昌网站建设 南昌做网站公司google chrome官网
  • 做黄金比较专业的网站网络推广平台有哪些渠道
  • 长春网站推广千锋教育培训收费一览表
  • 哪个网站代做ppt便宜惠州网站seo排名优化
  • 做外贸网站 深圳长沙网络推广外包
  • 写网站论文怎么做石家庄网站建设培训
  • 山东网站建设百度手机助手应用商店下载
  • 建设游戏网站需要哪些设备济南做网站公司哪家好
  • 济南 微网站搜索引擎seo关键词优化方法
  • 零基础做动态网站需要多久百度指数查询官网入口登录
  • wordpress 企业站外贸推广营销公司
  • 网站服务器配置如何让百度快速收录
  • 000webhost wordpress杭州百度seo代理
  • 兰州企业网站建设多少钱竞价恶意点击立案标准
  • 上海一网淘宝seo优化