一、封装一个函数来识别要解析的类型
get_type(){
if(this.url.match(/http[s]?://v.douyin.com/[^ ]+/) != null){
console.log("识别到【dy】链接")
return "dy"
}
else if(this.url.match(/http[s]?://v.kuaishou.com/[^ ]+/) != null){
console.log("识别到【ks】链接")
return "ks"
}
else if(this.url.match(/http[s]?://xhslink.com/[^ ]+/) != null){
console.log("识别到【xhs】链接")
return "xhs"
}
else{
console.log("未识别到链接类型,请输入正确的链接")
return null
}
}
二、在初始化方法中写入本实例共用的数据
constructor() {
this.token = "Z1QljZOZiT4NTG"
this.req_urls = {
dy: "http://api.txapi.cn/v1/parse_short_video/dy",
ks: "http://api.txapi.cn/v1/parse_short_video/ks",
xhs: "http://api.txapi.cn/v1/parse_short_video/xhs",
}
this.url = ''
this.type = ''
}
三、封装一个“万能解析”的方法
parse_video(){
axios({
url: this.req_urls[this.type],
method: 'POST',
headers: {
'Content-Type': "application/x-www-form-urlencoded"
},
responseType: 'json',
data: {
token: this.token,
url: this.url
}
})
.then(resp => {
if(resp.data.code != 200 && resp.data.msg != "OK"){
console.log("解析失败")
}
else{
const data = resp.data.data
console.log(data)
var type = data.type
var title = data.title
var cover_url = data.cover_url
var video_url = data.video_url
var imgs = data.imgs
}
})
}
废话不多说 直接上完整代码👇
const axios = require('axios')
class Parse{
constructor() {
this.token = "Z1QljZOZiT4NTG"
this.req_urls = {
dy: "http://api.txapi.cn/v1/parse_short_video/dy",
ks: "http://api.txapi.cn/v1/parse_short_video/ks",
xhs: "http://api.txapi.cn/v1/parse_short_video/xhs",
}
this.url = ''
this.type = ''
}
parse_video(){
axios({
url: this.req_urls[this.type],
method: 'POST',
headers: {
'Content-Type': "application/x-www-form-urlencoded"
},
responseType: 'json',
data: {
token: this.token,
url: this.url
}
})
.then(resp => {
if(resp.data.code != 200 && resp.data.msg != "OK"){
console.log("解析失败")
}
else{
const data = resp.data.data
console.log(data)
var type = data.type
var title = data.title
var cover_url = data.cover_url
var video_url = data.video_url
var imgs = data.imgs
}
})
}
get_type(){
if(this.url.match(/http[s]?://v.douyin.com/[^ ]+/) != null){
console.log("识别到【dy】链接")
return "dy"
}
else if(this.url.match(/http[s]?://v.kuaishou.com/[^ ]+/) != null){
console.log("识别到【ks】链接")
return "ks"
}
else if(this.url.match(/http[s]?://xhslink.com/[^ ]+/) != null){
console.log("识别到【xhs】链接")
return "xhs"
}
else{
console.log("未识别到链接类型,请输入正确的链接")
return null
}
}
run(url){
this.url = url
this.type = this.get_type();
if(!this.type){
return
}
this.parse_video()
}
}
if(__filename === process.mainModule.filename) {
const p = new Parse()
p.run("https://v.douyin.com/hoDBW9H")
p.run("https://v.kuaishou.com/C75B2q")
p.run("http://xhslink.com/fKihbj")
}