一.抓取数组中的所有图片
1.先获取到所有的图片
var photo=$(item).find(".dynamic-album-desc a img");
2.对这个对象进行遍历
使用map方法更方便
var urls=photo.map((index,item)=>{
return $(item).attr("src")
})
3.通过展开的方法将对象添加到一个数组中
links.push({
urls:[...urls]
})
二.多个相同的模块需要遍历
const puppeteer=require('puppeteer');
const url="https://www.duitang.com/";
async function pic(){
const browser=await puppeteer.launch();
const page=await browser.newPage();
await page.goto(url,{
waitUntil:'networkidle2'
});
await page.waitFor(2000)
await page.hover(".content-detail .dynamic-feed-item")
let res=await page.evaluate(()=>{
var $=window.jQuery;
var items=$(".content-detail .dynamic-feed-item"); //抓取你要遍历的那一块
var links=[];
if(items.length>0){
items.each((index,item)=>{
var id=$(item).attr("data-id");
var img=$(item).find(".user-info a img").attr("src");
var username=$(item).find(".user-desc .username").html();
var author=$(item).find(".dynamic-album-desc").html();
var photo=$(item).find(".dynamic-multi-img-container a img");
var urls=photo.map((index,item)=>{
return $(item).attr("src")
})
var like=$(item).find(".de-action .like-action span").text();
var favorite=$(item).find(".de-action .favorite-action span").text();
links.push({
id,
img,
username,
author,
like,
favorite,
urls:[...urls],
})
})
}
return links;
})
browser.close();
return res
}
module.exports=pic;
三。只有一个模块不需要遍历
const puppeteer=require('puppeteer');
async function detail(url){
const browser=await puppeteer.launch();
const page=await browser.newPage();
await page.goto(url,{
waitUntil:'networkidle2'
});
await page.waitFor(2000)
let res=await page.evaluate(()=>{ //不用再去抓取某一块,直接取数据
var $=window.jQuery;
var img=$(".link img").attr("src");
var name=$(".author-info .name").text();
var author=$(".atlas-desc").text();
var photo=$(".atlas-item img");
var urls=photo.map((index,item)=>{
return $(item).attr("src")
})
var like=$(".like span").text();
var favorite=$(".collection span").text();
var Img=$(".sender-avatar img");
var value=$("#dt-search #type").attr("value");
var keyword=$("#dt-search .ipt").attr("name")
var url=Img.map((index,item)=>{
return $(item).attr("src")
})
return{
img,
name,
author,
like,
favorite,
urls:[...urls],
url:[...url],
value,
keyword
}
})
browser.close();
return res
}
module.exports=detail;