puppeteer 官方文档里的一段代码想改一下 https://pptr.dev/#?product=Puppeteer&version=v7.0.1&show=api-pagewaitforselectorselector-options
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
let currentURL;
page
.waitForSelector('img')
.then(() => console.log('First URL with image: ' + currentURL));
for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {
await page.goto(currentURL);
}
await browser.close();
})();
简单的 print 第一个有 img 的网站。想改成
const puppeteer = require('puppeteer');
const get_available_item = async (page) => {
let currentURL;
const urls = [
'https://example.com',
'https://example.com',
'https://baidu.com'
]
page.waitForSelector('img').then(
() => {
console.log('First URL with image: ' + currentURL)
}
);
for (currentURL of urls) {
await page.goto(currentURL, {waitUntil: 'load'});
}
};
const main = async () => {
const browser = await puppeteer.launch({
headless: false,
product: 'firefox',
defaultViewport: { width: 1366, height: 768 }
});
const page = await browser.newPage();
await get_available_item(page)
await browser.close();
}
main()
想让get_available_item
返回currentURL
,试了一种用 callback 返回的方法
const puppeteer = require('puppeteer');
const get_available_item = async (page, callback) => {
let currentURL;
const urls = [
'https://example.com',
'https://example.com',
'https://baidu.com'
]
page.waitForSelector('img').then(
() => {
callback(currentURL)
}
);
for (currentURL of urls) {
await page.goto(currentURL, {waitUntil: 'load'});
}
};
const main = async () => {
let url
const browser = await puppeteer.launch({
headless: false,
product: 'firefox',
defaultViewport: { width: 1366, height: 768 }
});
const page = await browser.newPage();
await get_available_item(page, (res) => {
url = res
})
console.log(`result is ${url}`)
await browser.close();
}
main()
有比 callback 更简洁的方法么?
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.