使用 Puppeteer 如何从目录上传随机文件并删除它?
With Puppeteer How To Upload Random Files From A Directory and Delete It?
我想用 node js 编写一个 puppeteer 脚本,将一个随机文件从目录上传到服务器并删除它。
这是站点中的 HTML 代码:
<form action="/server.php">
<input type="file" id="myFile" name="filename">
<input type="submit">
</form>
所以现在我需要从一个目录上传一个图像文件(但我不知道图像名称),然后我需要从目录中删除那个文件。
这是我当前的木偶操作代码:
//UPLOAD A PICTURE
const fileName = 'dont-know-the-name.png';
const picInput = await page.$('#myFile');
await picInput.uploadFile(fileName);
实际上,负责上传文件的是Puppeteer's ElementHandle.uploadFile()
method.. You would want to use Node's fs.readDir()
to get an array of the file in the dir, take a random element and then use fs.unlink()
删除文件。
这是一个实现:
const dir = "YOUR/DIR/PATH";
const rnd = (arr) => arr[Math.floor(Math.random() * arr.length)];
const rndFile = () => `${dir}/${rnd(fs.readdirSync(dir))}`;
(async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto("YOUR/UPLOAD/URL")
const file = rndFile();
const elementHandle = await page.$("input[type=file]");
await elementHandle.uploadFile(file);
await page.click("input[type=submit]")
fs.unlinkSync(file)
})();
我想用 node js 编写一个 puppeteer 脚本,将一个随机文件从目录上传到服务器并删除它。
这是站点中的 HTML 代码:
<form action="/server.php">
<input type="file" id="myFile" name="filename">
<input type="submit">
</form>
所以现在我需要从一个目录上传一个图像文件(但我不知道图像名称),然后我需要从目录中删除那个文件。
这是我当前的木偶操作代码:
//UPLOAD A PICTURE
const fileName = 'dont-know-the-name.png';
const picInput = await page.$('#myFile');
await picInput.uploadFile(fileName);
实际上,负责上传文件的是Puppeteer's ElementHandle.uploadFile()
method.. You would want to use Node's fs.readDir()
to get an array of the file in the dir, take a random element and then use fs.unlink()
删除文件。
这是一个实现:
const dir = "YOUR/DIR/PATH";
const rnd = (arr) => arr[Math.floor(Math.random() * arr.length)];
const rndFile = () => `${dir}/${rnd(fs.readdirSync(dir))}`;
(async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto("YOUR/UPLOAD/URL")
const file = rndFile();
const elementHandle = await page.$("input[type=file]");
await elementHandle.uploadFile(file);
await page.click("input[type=submit]")
fs.unlinkSync(file)
})();