はじめに
Web上の画像を自動で収集し、Googleドライブに保存したいと思ったことはありませんか?
この記事では、JavaでWebページから画像をスクレイピングし、Google Drive APIを使って自動保存する方法を解説します。
使用する主な技術
Jsoup
(HTMLスクレイピング)Google Drive API
(ファイルアップロード)OAuth2
(認証)
事前準備
1. 必要ライブラリの導入(Maven)
<!-- Jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.17.2</version>
</dependency>
<!-- Google Drive API -->
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-drive</artifactId>
<version>v3-rev20240115-2.0.0</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.34.1</version>
</dependency>
2. Google Cloud ConsoleでAPI設定
- https://console.cloud.google.com/ にアクセスし、新しいプロジェクトを作成
- 「Drive API」を有効化
- 「OAuth 2.0 クライアントID」を作成
credentials.json
をダウンロードして、プロジェクト内に保存
Webページから画像URLを取得(Jsoup)
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
public class ImageScraper {
public static List<String> extractImageUrls(String url) throws Exception {
Document doc = Jsoup.connect(url).get();
Elements images = doc.select("img[src]");
List<String> imageUrls = new ArrayList<>();
for (Element img : images) {
imageUrls.add(img.absUrl("src"));
}
return imageUrls;
}
}
Googleドライブに画像をアップロードする処理
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import java.io.InputStream;
import java.net.URL;
import java.util.Collections;
public class DriveUploader {
public static Drive createDriveService() throws Exception {
GoogleCredential credential = GoogleCredential
.fromStream(new java.io.FileInputStream("credentials.json"))
.createScoped(Collections.singleton("https://www.googleapis.com/auth/drive.file"));
return new Drive.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
credential
).setApplicationName("ImageUploader").build();
}
public static void uploadImage(Drive driveService, String imageUrl, String fileName) throws Exception {
InputStream inputStream = new URL(imageUrl).openStream();
File fileMetadata = new File();
fileMetadata.setName(fileName);
InputStreamContent mediaContent = new InputStreamContent("image/jpeg", inputStream);
driveService.files().create(fileMetadata, mediaContent).execute();
System.out.println("Uploaded: " + fileName);
}
}
メイン処理:スクレイピングとアップロードの連携
public class Main {
public static void main(String[] args) throws Exception {
List<String> imageUrls = ImageScraper.extractImageUrls("https://example.com");
Drive driveService = DriveUploader.createDriveService();
for (int i = 0; i < imageUrls.size(); i++) {
String imageUrl = imageUrls.get(i);
String fileName = "image_" + (i + 1) + ".jpg";
DriveUploader.uploadImage(driveService, imageUrl, fileName);
}
}
}
注意点
- 初回実行時はブラウザが開き、OAuth認証を求められます。
- 大量アップロード時にはGoogleのAPI制限に注意してください。
まとめ
JavaでWeb画像を自動収集し、Googleドライブに保存するまでの処理は、以下の3ステップで実現できます。
- Jsoupで画像URLを抽出
- Google Drive APIで認証・接続
- 画像をDriveへアップロード
業務自動化や情報収集の自動化ツールに活用できます。ぜひ活用してみてください。