如何使用 Flutter 从网站上抓取图像?

Kyl*_*ppe 6 android web-scraping flutter

嗨,我正在尝试执行从网站获取 img src url 的简单任务,但我似乎无法做到,我尝试了各种 flutter 包,现在我又恢复到了 vanilla Flutter。这是我的代码:

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);
              },
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明

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

在此处输入图片说明

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

jos*_*xha 4

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

  • 在您的 URL 前面写下http.get(),或右键单击该网站,然后单击“查看页面源代码”。现在 HTML 将以与您的应用程序获取它相同的方式显示。
  • 搜索avatar-wrapper round。您将无法找到它,因为此处尚不存在个人资料图片中的标签。
  • 幸运的是,个人资料图片的 URL 已经包含在其他地方。搜索<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('"'));
}
Run Code Online (Sandbox Code Playgroud)

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


编辑1:一般方法

  1. 查看页面源代码以查看页面的 HTML
  2. 搜索所需的子字符串。
  3. 选择前 10 到 15 个字符,查看该字符串之前出现的频率。
  4. 如果发生多次,您必须html = html.substring(html.indexOf(needle) + needle.length);经常重复拨打相应电话。
  5. 重新加载页面并检查它是否仍然有效。
  6. 现在你已经找到了你的针线。