问题:如何使用 Flutter 从网站上抓取图片?

嗨,我正在尝试做一个从网站获取 img src url 的简单任务,但我似乎做不到,我尝试了各种颤振包,现在我已经恢复到原版颤振。这是我的代码:

onPressed: () async {
                http.Response response = await http.get('https://tiktok.com/@$enteredUsername');
                dom.Document document = parser.parse(response.body);
                final elements = document.getElementsByClassName('jsx-581822467');
                print(elements);
              },

我只是想从这个网站(tiktok.com)获取图像 URL:

在此处输入图像描述

我查看了源代码,它说类名是“jsx-581822467”,但是如果我尝试在代码中使用它,它会返回一个空白列表。

在此处输入图像描述

我怎样才能简单地获取此个人资料图片的 URL?其他以“jsx”前缀作为类名的元素呢?

解答

我想我知道你的问题是什么。 Web 浏览器的检查器在 TikTok 个人资料页面上显示 HTML。但是,这仅在页面加载后使用 JavaScript 生成。如果我们通过http.get()下载内容,我们会在 JavaScript 进行任何更改之前获得原始 HTML。

  • 在你的 URL 前面写http.get(),或者在网站上右键点击查看页面源。现在 HTML 将以与您的应用程序获取它相同的方式显示。

  • 搜索avatar-wrapper round。您将无法找到它,因为个人资料图片中的标签在此处尚不存在。

  • 还好头像的网址已经包含在其他地方了。搜索<meta property="og:image" content="。你会发现只有一次点击,点击后头像的 URL 直接开始。

因此,在我看来,获取 URL 的最简单方法是:

1.下载HTML。

2.删除<meta property="og:image" content="之前的所有文字。

3.直到下一个"的所有字符都是我们要查找的URL。

在这里,我插入了我的代码,对我来说效果很好:

Future<String> getProfileImageUrl(String username) async {
  // Download the content of the site
  http.Response response = await http.get("https://www.tiktok.com/@$username");
  String html = response.body;

  // The html contains the following string exactly one time.
  // After this specific string the url of the profile picture starts. 
  String needle = '<meta property="og:image" content="';
  int index = html.indexOf(needle);

  // The result of indexOf() equals -1 if the needle didn't occurred in the html.
  // In that case the received username may be invalid.
  if (index == -1)
    return null;

  // Remove all characters up to the start of the text snippet that we want.
  html = html.substring(html.indexOf(needle) + needle.length);

  // return all chars until the first occurrence of '"'
  return html.substring(0, html.indexOf('"'));
}

我希望我的解释能帮助你。


编辑 1:一般方法

1.查看页面源码查看页面的HTML

  1. 搜索所需的子字符串。

  2. 选择前面的 10 到 15 个字符,看看这个字符串之前出现的频率。

4、如果出现不止一次,则必须相应地经常重复调用html = html.substring(html.indexOf(needle) + needle.length);

5.重新加载页面并检查它是否仍然有效。

  1. 现在你已经找到你的针线了。
Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐