如何从flutter中的html过滤img标签

莎莉亚·拉菲克(Shahryar Rafique)

我正在使用WordPress rest API开发应用程序。在WordPress rest API post中,有一个名为content的属性该属性具有进一步的属性,如Json所示。在rendered属性中有一个html标签。我只想从那里过滤img标签。如何在Dart或php中实现此目的?

        "id": 1660,
        "link": "http://localhost/soledesign/bill-baber/",
        "title": {
            "rendered": "Bill Baber"
        },
        "content": {
            "rendered": "<h2>Bill Baber Knitwear opened our doors for the first time back in 1977 and have been producing the finest Scottish knitwear ever since.</h2>\n<p>Helen &amp; Bill Baber design and produce the whole collection themselves, with a little help from time to time. The collection includes mostly ladies wear, with some unisex styles, sorry guys! You’ll find full length silk jackets, luxuriously soft cashmere shawls, lightweight linen tops and stunning accessories to pep up any outfit. The widest selection can be found in store at <a href=\"https://billbaber.com/contact-us/\">66 Grassmarket</a>, however we do have a collection available <a href=\"https://billbaber.com/shop/\">online</a> for you to enjoy and we even supply other <a href=\"https://billbaber.com/stockists/\">retailers</a> all over the world!</p>\n<p>On this site you will see garments that we carry in stock or produce to order. in some cases we may hold a little stock ready to go, but generally each items is made from scratch when you order it. In store we have a boutique collection many of which simply cannot be reproduced, sometimes the yarn has run out or the style was a one off creation.</p>\n<p>&nbsp;</p>\n<p><img src=\"https://billbaber.com/wp-content/uploads/2019/09/crail_silver-190x285.jpg\" alt=\"Crail Top\" /><img src=\"https://billbaber.com/wp-content/uploads/2019/09/liscannor_crew-190x285.jpg\" alt=\"Crew Jumper\" /><img src=\"https://billbaber.com/wp-content/uploads/2017/09/t_alt_dne-190x285.jpg\" alt=\"Alto Top\" /><img src=\"https://billbaber.com/wp-content/uploads/2017/09/t_dtt_sge-190x285.jpg\" alt=\"Dot\" /></p>\n<p>&nbsp;</p>\n",
            "protected": false
        },
        "excerpt": {
            "rendered": "<p>Bill Baber Knitwear opened our doors for the first time back in 1977 and have been producing the finest Scottish knitwear ever since. Helen &amp; Bill Baber design and produce the whole collection themselves, with a little help from time to time. The collection includes mostly ladies wear, with some unisex styles, sorry guys! You’ll [&hellip;]</p>\n",
            "protected": false
        },
        "author": 83
    },
chunhunghan

您可以在下面复制粘贴运行完整的代码。
您可以使用包https://pub.dev/packages/html。
步骤1:删除特殊字符并解析json字符串,可以看到Payload完整代码中的类

String result = jsonString.replaceAll("\n", "");
Payload payload = payloadFromJson(result);

第2步:DOM ElementquerySelectorAll("img")

import 'package:html/parser.dart' show parse;
import 'package:html/dom.dart' as dom;
...    

var document = parse(payload.content.rendered);
var imgList = document.querySelectorAll("img");

for (dom.Element img in imgList) {
  print(img.attributes["src"]);
  print(img.toString());
}

输出

I/flutter (11892): https://billbaber.com/wp-content/uploads/2019/09/crail_silver-190x285.jpg
I/flutter (11892): https://billbaber.com/wp-content/uploads/2019/09/liscannor_crew-190x285.jpg
I/flutter (11892): https://billbaber.com/wp-content/uploads/2017/09/t_alt_dne-190x285.jpg
I/flutter (11892): https://billbaber.com/wp-content/uploads/2017/09/t_dtt_sge-190x285.jpg

工作演示

在此处输入图片说明

完整的代码

import 'package:flutter/material.dart';
import 'package:html/parser.dart' show parse;
import 'package:html/dom.dart' as dom;
import 'dart:convert';

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
  int id;
  String link;
  Title title;
  Content content;
  Content excerpt;
  int author;

  Payload({
    this.id,
    this.link,
    this.title,
    this.content,
    this.excerpt,
    this.author,
  });

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        id: json["id"],
        link: json["link"],
        title: Title.fromJson(json["title"]),
        content: Content.fromJson(json["content"]),
        excerpt: Content.fromJson(json["excerpt"]),
        author: json["author"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "link": link,
        "title": title.toJson(),
        "content": content.toJson(),
        "excerpt": excerpt.toJson(),
        "author": author,
      };
}

class Content {
  String rendered;
  bool protected;

  Content({
    this.rendered,
    this.protected,
  });

  factory Content.fromJson(Map<String, dynamic> json) => Content(
        rendered: json["rendered"],
        protected: json["protected"],
      );

  Map<String, dynamic> toJson() => {
        "rendered": rendered,
        "protected": protected,
      };
}

class Title {
  String rendered;

  Title({
    this.rendered,
  });

  factory Title.fromJson(Map<String, dynamic> json) => Title(
        rendered: json["rendered"],
      );

  Map<String, dynamic> toJson() => {
        "rendered": rendered,
      };
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Future<List<String>> _future;

  Future<List<String>> _getData() {
    String jsonString = r'''
    {
    "id": 1660,
        "link": "http://localhost/soledesign/bill-baber/",
        "title": {
            "rendered": "Bill Baber"
        },
        "content": {
            "rendered": "<h2>Bill Baber Knitwear opened our doors for the first time back in 1977 and have been producing the finest Scottish knitwear ever since.</h2>\n<p>Helen &amp; Bill Baber design and produce the whole collection themselves, with a little help from time to time. The collection includes mostly ladies wear, with some unisex styles, sorry guys! You’ll find full length silk jackets, luxuriously soft cashmere shawls, lightweight linen tops and stunning accessories to pep up any outfit. The widest selection can be found in store at <a href=\"https://billbaber.com/contact-us/\">66 Grassmarket</a>, however we do have a collection available <a href=\"https://billbaber.com/shop/\">online</a> for you to enjoy and we even supply other <a href=\"https://billbaber.com/stockists/\">retailers</a> all over the world!</p>\n<p>On this site you will see garments that we carry in stock or produce to order. in some cases we may hold a little stock ready to go, but generally each items is made from scratch when you order it. In store we have a boutique collection many of which simply cannot be reproduced, sometimes the yarn has run out or the style was a one off creation.</p>\n<p>&nbsp;</p>\n<p><img src=\"https://billbaber.com/wp-content/uploads/2019/09/crail_silver-190x285.jpg\" alt=\"Crail Top\" /><img src=\"https://billbaber.com/wp-content/uploads/2019/09/liscannor_crew-190x285.jpg\" alt=\"Crew Jumper\" /><img src=\"https://billbaber.com/wp-content/uploads/2017/09/t_alt_dne-190x285.jpg\" alt=\"Alto Top\" /><img src=\"https://billbaber.com/wp-content/uploads/2017/09/t_dtt_sge-190x285.jpg\" alt=\"Dot\" /></p>\n<p>&nbsp;</p>\n",
            "protected": false
        },
        "excerpt": {
            "rendered": "<p>Bill Baber Knitwear opened our doors for the first time back in 1977 and have been producing the finest Scottish knitwear ever since. Helen &amp; Bill Baber design and produce the whole collection themselves, with a little help from time to time. The collection includes mostly ladies wear, with some unisex styles, sorry guys! You’ll [&hellip;]</p>\n",
            "protected": false
        },
        "author": 83
}
    ''';

    String result = jsonString.replaceAll("\n", "");
    Payload payload = payloadFromJson(result);
    var document = parse(payload.content.rendered);
    var imgList = document.querySelectorAll("img");
    List<String> imageList = [];
    for (dom.Element img in imgList) {
      print(img.attributes["src"]);
      imageList.add(img.attributes["src"]);
    }
    return Future.value(imageList);
  }

  @override
  void initState() {
    _future = _getData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder<List<String>>(
            future: _getData(),
            builder: (BuildContext context, AsyncSnapshot<List<String>> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('Input a URL to start');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount:
                            snapshot.data.length,
                        itemBuilder: (context, index) {
                          return ListTile(
                            title: Text(snapshot.data[index]),
                          );
                        });
                  }
              }
            }));
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何调整HTML中img标签中使用的svg的大小?

HTML-如何在img标签中显示本地数据?

在Material-ui卡组件中如何使用Video html标签而不是img标签

如何在 sublime 文本中的 HTML 标签 a 内快速键入标签 img?

在javascript中返回html img标签

如何为<img>标签创建过滤器?

如何从 html 中获取图像,图像不在 img 标签中,而是在 div class='blah blah' 下

如何从VBA中的img标签解析src

如何在ERB中编写像<img>标签这样的纯HTML?

Postman 可视化 - 如何在简单的 HTML img 标签中呈现图像 URL

如何从c#中的img html标签获取图像源属性值?

如何在我的 HTML <img> 标签顶部显示 JS 中的捕捉网格?

如何使用正则表达式从 javascript 中的 HTML 标签中过滤字符串

如何在 <option> 标签中插入 <img> 标签?

如何从数组中过滤掉 HTML 标签并用空替换?

如何将所有HTML img close标签转换为XML兼容?(<img>至<img />)

在Powershell中的HTML文件中查找<img>标签

如何在flutter中传递HTML标签中的变量并加载到WebView中

标签标签如何在HTML中工作

如何将 HTML img 标签与属性匹配

如何显示来自 api 的 <img src> html 标签的图像?

将PHP变量传递给HTML img标签中的src

如何在 Flutter 中过滤未来列表?

如何在 Flutter 中过滤列表?

如何通过php过滤给定数量的html标签

如何在wordpress中获取img标签的图像URL

在PHP中,如何保留img标签的样式属性

如何使用XML文件结构中的IMG标签

如何在img标签中更改svg源的颜色?