1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Flutterでもスクレイピングがしたい

Last updated at Posted at 2022-05-30

目次

  1. 準備
  2. WindowControllerでhtmlを取得する
  3. 要素を探す
  4. 欲しい値を取得する
  5. コード全文

準備

universal_htmlというライブラリを使います
https://pub.dev/packages/universal_html
pubspec.yamlに下記を追加
universal_html: ^2.0.8

WindowControllerでhtmlを取得する

WindowControllerでhtmlを取得します
今回はQiitaのトレンドページから記事一覧を取得します

final url = 'https://qiita.com/trend'
final controller = WindowController();
await controller.openHttp(uri: Uri.parse(url));

要素を探す

querySelectorAllというメソッドで要素を探します

final elements = controller.window!.document.querySelectorAll("article > h2 > a");

今回は要素を特定するのにhtmlタグを使っていますがclass名を使うこともできます
(例)

final elements = controller.window.document.querySelectorAll(".className > .className2 > a");

欲しい値を取得する

elements.forEach((element) {
  final title = element.innerHtml;
  final href = element.attributes['href'];
});

コード全文

コピペ用です
強制アンラップしているので気をつけてください

import "package:universal_html/controller.dart";

final url = 'https://qiita.com/trend'
final controller = WindowController();
await controller.openHttp(uri: Uri.parse(url));
final elements = controller.window!.document.querySelectorAll("article > h2 > a");

elements.forEach((element) {
  final title = element.innerHtml;
  final href = element.attributes['href'];
});
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?