playwright使用
Playwright是一种用于编写Web自动化测试和爬虫的开源工具。它支持多种浏览器(Chrome,Edge,Firefox和Safari)和多种编程语言(JavaScript,TypeScript,Python和Java)。以下是一些使用Playwright的示例:
1.安装Playwright:
npm install playwright
2.启动浏览器(例如Chrome):
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://www.baidu.com');
await browser.close();
})();```
3.执行搜索操作:
```const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://www.baidu.com');
await page.type('input[name="wd"]', 'playwright');
await page.click('input[type="submit"]');
await browser.close();
})();```
4.使用断言验证搜索结果:
```const { chromium } = require('playwright');
const assert = require('assert');
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://www.baidu.com');
await page.type('input[name="wd"]', 'playwright');
await page.click('input[type="submit"]');
const searchResult = await page.$eval('.result-op', el => el.textContent);
assert(searchResult.includes('Playwright - GitHub'), 'Search result not found');
await browser.close();
})();```
5.使用Playwright编写爬虫:
```const { chromium } = require('playwright');
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://www.example.com');
const links = await page.$$eval('a', els => els.map(el => el.href));
console.log(links);
await browser.close();
})();```
这些示例只是Playwright的一小部分功能。Playwright还支持截图,PDF生成,录制,模拟设备,网络拦截和更多功能。
原文地址: https://www.cveoy.top/t/topic/b0QD 著作权归作者所有。请勿转载和采集!