嗨,我正在尝试做一个简单的任务,从网站获取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:
我已经查看了源代码,它说类名是'jsx-581822467',但是如果我尝试在代码中使用它,它将返回一个空白列表。
如何仅获取此个人资料图片的URL?还有其他带有“ jsx”前缀作为其类名的元素?
答案 0 :(得分:3)
我想我知道您的问题是什么。 Web浏览器的检查器在TikTok配置文件页面上显示HTML。但是,仅在页面加载后使用JavaScript生成。如果我们通过http.get()
下载内容,那么在JavaScript进行任何更改之前,我们将获取原始HTML。
http.get(),
或右键单击网站,然后点击查看页面源代码。现在,HTML将以您的应用获取HTML的相同方式显示。avatar-wrapper round
。您将无法找到它,因为个人资料图片中的标签在此尚不存在。<meta property="og:image" content="
。您只会找到一个匹配项,匹配项后,个人资料图片的网址将直接启动。 因此,我认为获取URL的最简单方法是:
<meta property="og:image" content="
。"
后面的所有字符都是我们要查找的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:常规方法
html = html.substring(html.indexOf(needle) + needle.length);
。