当前位置:网站首页>Playwirght深度入门
Playwirght深度入门
2022-06-23 07:01:00 【罗汉翔】
参考链接:
目录
一、pom依赖
从你认识Playwright这个单词起,你就离不开它的pom依赖,来往下看:
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.20.0</version>
</dependency>二、认识Playwright Inspector小工具
它可以记录你的操作行为,生成代码。
在Java环境下的IDEA中的Terminal中输入,即可打开Playwright Inspector:
mvn exec:java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args="codegen wikipedia.org"
(将“wikipedia.org”换成能够正常打开的网站即可)
第一次写完程序运行时,如果没有在程序中进行相关设置,会下载palywright自带浏览器内置浏览器二进制文件,需要等待一会。
建议使用mvn命令编译,这样能看到浏览器下载进度
mvn compile exec:java -Dexec.mainClass="org.example.Example"(没试过)
三、打开网页6步走
1、Playwright
生成默认的的playwright Playwright playwright = Playwright.create()
或:
生成附加相关配置的Playwright
Playwright.CreateOptions createOptions = new Playwright.CreateOptions();
Map<String, String> map = new HashMap<>();
// 设置忽略下载浏览器,如果值为0,则下载Playwright默认的浏览器。(蓝色图标的chrome)
map.put("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "1");
createOptions.setEnv(map);
Playwright playwright = Playwright.create(createOptions);2、Browser
switch (name) {
case "firefox":
return playwright.firefox().launch();
case "chromium":
BrowserType.LaunchOptions chromeLaunchOptions = new BrowserType.LaunchOptions();
chromeLaunchOptions.setHeadless(false);
// 指定浏览器类型
chromeLaunchOptions.setChannel("chrome");
// 指定浏览器的执行目录
chromeLaunchOptions.setExecutablePath(Paths.get(new File(LocalChromePath).toURI()));
// 指定超时时间
chromeLaunchOptions.setTimeout(120 * 1000);
return playwright.chromium().launch(chromeLaunchOptions);
case "webkit":
return playwright.webkit().launch();3、BrowserContext
if (isMobile) {
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setUserAgent("Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36")
.setViewportSize(411, 731)
.setDeviceScaleFactor(2.625)
.setLocale("zh-CN")
.setIsMobile(true)
.setHasTouch(true)
.setLocale("en-US")
.setGeolocation(41.889938, 12.492507)
.setPermissions(Arrays.asList("geolocation")));
return context;
} else {
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setIgnoreHTTPSErrors(true)
.setJavaScriptEnabled(true)
.setViewportSize(1920, 1080)
.setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.130 Safari/537.36"));
return context;
}4、Page
Page page = browser.newPage();
或:
Page page = browserContext.newPage(); 有了page实例以后:
// 执行js
page.addInitScript("Object.defineProperties(navigator, {webdriver:{get:()=>undefined}});");// 执行js
Object dimensions = page.evaluate("() => {\n" +
" return {\n" +
" width: document.documentElement.clientWidth,\n" +
" height: document.documentElement.clientHeight,\n" +
" deviceScaleFactor: window.devicePixelRatio\n" +
" }\n" +
"}");
// WindowDimensions:====>{width=1920, height=1080, deviceScaleFactor=1}
System.out.println("WindowDimensions:====>" + dimensions);
page.route("**", route -> {
System.out.println("RouteUrl:====>" + route.request().url());
route.resume();
});5、打开网页
String targetUrl = "https://www.bbsmax.com"; page.navigate(targetUrl , new Page.NavigateOptions().setTimeout(120 * 1000));
6、有同学说了,我要内容
// 内容这不就来了吗 String content = page.content();
// 中途可以把Playwright Inspector窗口调出来方便调试,程序也会停在这里。
page.pause();
7、最后有头有尾来个finally, close掉
BrowserContext context = page.context(); Browser browser = context.browser(); page.close(); context.close(); browser.close();
如果当前你的BrowserContext、Browser 、Page实例就在当前的作用域中,直接调用实例的close方法即可,不必通过page.context()获取BrowserContext。

边栏推荐
- SimpleDateFormat 线程安全问题
- 【AI实战】XGBRegressor模型加速训练,使用GPU秒级训练XGBRegressor
- leetcode210. Schedule II 207 Curriculum topology sorting DFS BFS
- MySQL (11) - sorting out MySQL interview questions
- Unity图片加载和保存
- 左乘右乘矩阵问题
- RTMP streaming exception fast recovery scheme
- 论文写作之WPS安装Mathtype插件编写数学公式
- Online text filter less than specified length tool
- HCIP之路第八次实验
猜你喜欢

U-Net: Convolutional Networks for Biomedical Image Segmentation

Cirium has gradually become the standard for airlines' carbon dioxide emission reporting

Detailed explanation of redis persistence, master-slave and sentry architecture

MySQL Niuke brush questions

论文写作之WPS安装Mathtype插件编写数学公式

1278_FreeRTOS_借助prvAddCurrentTaskToDelayedList接口理解delayed task

Both are hard disk partitions. What is the difference between C disk and D disk?

《一周的朋友》

User mode and kernel mode

30 sets of report templates necessary for the workplace, meeting 95% of the report needs, and no code is required for one click application
随机推荐
干货来了|《PaaS》合辑抢先看~
[pit stepping record] a pit where the database connection is not closed and resources are released
How bootstrap clears floating styles
Design of temperature detection and alarm system based on 51 single chip microcomputer
leetcode210. Schedule II 207 Curriculum topology sorting DFS BFS
【markdown】markdown 教程大归纳
职场必备的30套报表模板,满足95%的报表需求,一键套用无需代码
Elaborate on the operation of idea
[Planet selection] how to efficiently build fine-grained two-way links between roam and thebrain?
Akamai-1.75 version-_ Abck parameter generation JS reverse analysis
MySQL (IV) - MySQL storage engine
MySQL (V) - locks and transactions
To conquer salt fields and vegetable fields with AI, scientific and technological innovation should also step on the "field"
[AI practice] xgb Xgbregression multioutputregressor parameter 2 (GPU training model)
Product axure9 (English version), prototype design background dynamic secondary menu display content
Ntu-rgbd data set download and data format analysis
跳跃表原理
RFID data security experiment: C # visual realization of parity check, CRC redundancy check and Hamming code check
[deep learning] [original] how to detect targets and draw map and other parameter maps without yolov5 weights or models
Ldconfig command