Java ファンクションスタックで Headless に接続
このセクションでは、お好みのブラウザ自動化ライブラリを使用して、Java ファンクションスタックでヘッドレスリモートブラウザに接続するために必要なスクリプトを紹介します。
注意: Puppeteer は Java ファンクションスタックでは利用できません。
Playwright
SmartBrowz なしで Playwright を使用する場合
copy
package org.example;
import com.microsoft.playwright.*;
import java.nio.file.Paths;
public class PlaywrightJava {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
try (Browser browser = playwright.chromium().launch()) {
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.navigate("http://example.com/"");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png")));
}
}
}
}
SmartBrowz で Playwright を使用する場合
copy
// Javaアプリケーション内から
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType browserType = playwright.chromium();
//browserType.launchをconnectOverCDPに変更する
Browser browser = browserType.connectOverCDP("YOUR_CDP_ENDPOINT");
// コードの残りの部分は同じです
Page page = browser.newPage();
page.navigate("https://www.example.com");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png")));
}
}
注意: コンソールに表示されている CDP エンドポイントをコピーし、このコードを実装する際に「8」行目に貼り付けてください。
Selenium
SmartBrowz なしで Selenium を使用する場合
copy
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.IOException;
public class ScreenshotDemo {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path\to\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://demoqa.com");
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenshot, new File("path\\to\\homePageScreenshot.png"));
} catch (IOException e) {
System.out.println(e.getMessage());
}
driver.close();
}
}
SmartBrowz で Selenium を使用する場合
copy
// Javaアプリケーション内から
public static void main() throws MalformedURLException {
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--no-sandbox");
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--disable-dev-shm-usage");
//ChromeDriverをRemoteWebDriverに変更する
WebDriver driver = new RemoteWebDriver(new URL("YOUR_WEBDRIVER_ENDPOINT"),chromeOptions);
// コードの残りの部分は同じです
driver.get("https://www.example.com");
driver.quit();
}
注意: コンソールから Webdriver エンドポイントをコピーし、このコードを実装する際に「9」行目に貼り付けてください。
最終更新日 2026-03-30 13:40:30 +0530 IST
Yes
No
Send your feedback to us
Skip
Submit