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

时间:2020-05-29 17:59:50

标签: android flutter web-scraping

嗨,我正在尝试做一个简单的任务,从网站获取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);
              },

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

enter image description here

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

enter image description here

如何仅获取此个人资料图片的URL?还有其他带有“ jsx”前缀作为其类名的元素?

1 个答案:

答案 0 :(得分:3)

我想我知道您的问题是什么。 Web浏览器的检查器在TikTok配置文件页面上显示HTML。但是,仅在页面加载后使用JavaScript生成。如果我们通过http.get()下载内容,那么在JavaScript进行任何更改之前,我们将获取原始HTML。

  • 在网址前面写上http.get(),或右键单击网站,然后点击查看页面源代码。现在,HTML将以您的应用获取HTML的相同方式显示。
  • 搜索avatar-wrapper round。您将无法找到它,因为个人资料图片中的标签在此尚不存在。
  • 幸运的是,个人资料图片的URL已经包含在其他地方。搜索<meta property="og:image" content="。您只会找到一个匹配项,匹配项后,个人资料图片的网址将直接启动。

因此,我认为获取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
  2. 搜索所需的子字符串。
  3. 选择前10到15个字符,然后查看此字符串之前出现的频率。
  4. 如果发生不止一次,则必须经常反复相应地致电html = html.substring(html.indexOf(needle) + needle.length);
  5. 重新加载页面并检查它是否仍然有效。
  6. 现在您已经找到了针线。
相关问题