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”前缀作为类名的元素?
我想我明白你的问题是什么了。网络浏览器的检查器会在 TikTok 个人资料页面上显示 HTML。但是,这仅在页面加载后使用 JavaScript 生成。如果我们通过 下载内容http.get(),我们会在 JavaScript 进行任何更改之前获得原始 HTML。
http.get(),或右键单击该网站,然后单击“查看页面源代码”。现在 HTML 将以与您的应用程序获取它相同的方式显示。avatar-wrapper round。您将无法找到它,因为此处尚不存在个人资料图片中的标签。<meta property="og:image" content="。您只会发现一次点击,点击后,个人资料图片的 URL 直接开始。因此,在我看来,获取 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('"'));
}
Run Code Online (Sandbox Code Playgroud)
我希望我的解释能帮助你。
编辑1:一般方法
html = html.substring(html.indexOf(needle) + needle.length);经常重复拨打相应电话。| 归档时间: |
|
| 查看次数: |
1472 次 |
| 最近记录: |