// 获取HTML
const BHtml = await superagent
.get(this.url);
// 打印结果
console.log(BHtml)
}
static init(url: string, cookie: string) {
if (!BC.Bilibili) {
BC.Bilibili = new BC(url, cookie);
}
return BC.Bilibili;
}
}
BC.init(“https://www.bilibili.com/”)
写完,运行编译命令
npm run dev
好家伙,直接403被拒绝了,这就尴尬了,老老实实打开B站,打开控制台,打开network,看看具体请求,是不是漏了什么,确实漏了,漏了cookie,通过请求得知,不管有没有登录都一定会带cookie信息,并且即使没有登录这个cookie也是有值的,只是不知道这个值代表什么意思,既然发现了,那就加上
/**
- @description 程序本体
*/
import superagent from “superagent”;
export default class BC {
private static Bilibili: BC;
constructor(private url: string, private cookie: string) {
this.start();
}
private async start() {
// 获取HTML
const BHtml = await superagent
.get(this.url)
.set(“cookie”, this.cookie);
// 打印结果
console.log(BHtml)
}
static init(url: string, cookie: string) {
if (!BC.Bilibili) {
BC.Bilibili = new BC(url, cookie);
}
return BC.Bilibili;
}
}
继续使用命令,运行代码,好家伙,真的取到了整个HTML代码,虽然这个HTML代码完全没有办法阅读,但是没关系,到这里基本已经确定了,方向上是对的,只是继续优化而已;
这里就要说到另外一个工具了,强烈推荐,cheerio,对应的官网在这里:cheerio官网,这是一个对JQ核心功能的实现:对DOM的操作,它能在服务端,对有DOM组成的字符串直接进行操作,直接先看个例子吧:
var cheerio = require(‘cheerio’),
$ = cheerio.load(‘
Hello world
’);$(‘h2.title’).text(‘Hello there!’);
$(‘h2’).addClass(‘welcome’);
$.html();
这个例子来自于网上,虽然简单,但是它一定程度上说明了这个插件的