我需要为Dart/Flutter应用程序收集一些数据,我需要登录才能访问该页面。
如何提交对表单数据的更改并单击登录按钮?我尝试了如下:
var loginPage = await http.get('https://mypage.com/login');
var document = parse(loginPage.body);
var username = document.querySelector('#username') as InputElement;
var password = document.querySelector('#password') as InputElement;
username.value = 'USERNAME';
password.value = 'PASSWORD';
var submit = document.querySelector('.btn-submit') as ButtonElement;
submit.click();
但我有以下错误:
Error: 'InputElement' isn't a type.
Error: 'ButtonElement' isn't a type.
我还尝试了以下内容:
InputElement username = document.querySelector('#username');
但是一个得到错误A value of type 'Element' can't be assigned to a variable of type 'InputElement'
我需要在flutter应用程序中进行此刮取,以避免使用API传递密码。
如何登录页面以获取数据?
InputElement
和ButtonElement
是dart:html
包的一部分,因此,我们不应该忘记在我们的代码中导入它:
import 'dart:html';
import 'package:http/http.dart' as http;
void submitForm() async {
var loginPage = await http.get('https://mypage.com/login');
var document = parse(loginPage.body);
var username = document.querySelector('#username') as InputElement;
var password = document.querySelector('#password') as InputElement;
username.value = 'USERNAME';
password.value = 'PASSWORD';
var submit = document.querySelector('.btn-submit') as ButtonElement;
submit.click();
}
通过这样做,编译器将把InputElement
和ButtonElement
识别为正确的类型。
另一种更优雅的方法是:
import 'dart:html';
import 'package:http/http.dart' as http;
void submitForm() async {
var loginPage = await http.get('https://mypage.com/login');
Document document = parse(loginPage.body);
(document.querySelector('#username') as InputElement).value = 'USERNAME';
(document.querySelector('#password') as InputElement).value = 'PASSWORD';
(document.querySelector('.btn-submit') as ButtonElement).click();
}
如果我们想在Flutter项目中使用相同的功能,我们可能需要universal_html
包的帮助:
- 将其添加到包的pubspec.yaml文件中:
dependencies:
universal_html: ^1.2.3
运行
flutter pub get
导入包并使用代码:
import 'package:http/http.dart' as http;
import 'package:universal_html/html.dart';
void submitForm() async {
var loginPage = await http.get('https://mypage.com/login');
Document document = parse(loginPage.body);
(document.querySelector('#username') as InputElement).value = 'USERNAME';
(document.querySelector('#password') as InputElement).value = 'PASSWORD';
(document.querySelector('.btn-submit') as ButtonElement).click();
}