当前位置: 首页 > 后端技术 > Node.js

使用TS爬虫爬取百度武汉疫情数据

时间:2023-04-03 14:11:06 Node.js

最近的疫情比较严重。每天醒来看着疫情的通报数据,就想着用科技做一些简单的事情。是否可以抓取百度在线公布的疫情数据?网址:https://voice.baidu.com/act/n...中间红框内的数据选择TypeScript,练习TS的语法和使用1.创建目录初始化新建目录spiderTS初始化npminit-y,初始化TS配置tsc--init,生成tsconfig.json文件目录结构如下2.爬取数据处理src目录下主要有两个文件:spider.ts//爬取数据并写入itintothefilewhCovid19Data.ts//Processdata爬取网页的数据,主要使用superagent库,使用superagent.get(url)方法获取TS写的页面数据,所以要安装dsuperagent的.ts库文件执行npminstall--save@types/superagent代码如下:`importpathfrom'path'importWhCovid19Datafrom'./WhCovid19Data';constwhCovid19Data=WhCovid19Data.getInstance();classSpider{privatefilePath=path.resolve(__dirname,'../data/data.json')constructor(){this.getHtmlContent();}asyncgetHtml(){consturl=awaitwhCovid19Data.getUrl();constres=awaitsuperagent.get(url)returnres.text;}writeFile(content:string){fs.writeFileSync(this.filePath,content)}asyncgetHtmlContent(){consthtmlContent=awaitthis.getHtml();constfileContent=whCovid19Data.handleData(htmlCon帐篷);this.writeFile(fileContent);}}constspider=newSpider();`2.whCovid19Data处理数据cheerio库用于处理网页数据,类似jquery的语法,获取对应的数据,安装对应的即可,cheerio.d.ts文件需要通过右键获取-点击网页查看以上数据,但是截取了源码,完全不一样(可以在网页上右击查看源码)。推测百度应该使用了类似react的第三方框架。动态渲染数据,SEO下无法抓取标签对应的数据怎么办?我进一步全局搜索了源代码,找到了我需要的数据。我在