写一个简易爬虫
Deno目前三方库支持度并不够,所以需要额外使用一些库,可以采用jspm来引入三方库
import xxx from "https://dev.jspm.io/xxx";
1.获取网页Dom
/**
* @subscribe Load file convert to html string
* @param url
* @param path
*/
export async function loadHtml(url:string){
const res = await fetch(url);
const htmlData = new Uint8Array(await res.arrayBuffer());
let htmlString = "";//
for (var i = 0; i < htmlData.length; i++) {
htmlString += String.fromCharCode(htmlData[i]);
}
return htmlString;
}
2.引入cheerio
cheerio用法类似JQuery, 可以通过选择器来选取相应DOM节点,attr获取DOM属性
import cheerio from "https://dev.jspm.io/cheerio";
3.抓取页面信息
/**
* get suburl form html string
* @param htmlString
*/
export function getSubUrl(htmlString:any){
let $ = cheerio.load(htmlString);
let lis = $(".pg-goods-list li a");
let hrefList:any = [];
lis.each((i:number,elem:any)=>{
hrefList.push($(elem).attr('href'))
});
let subUrlList = [...new Set(hrefList)];
return subUrlList;
}
4.注意
确保运行ts文件时增加权限属性--allow-net,如果只增加单一域名可以使用--allow-net=xxx.com deno run --allow-net .\src\job.ts