如何使用JavaScript元素抓取生成某些内容的网页?这是我的壁球俱乐部的当地法院预订网站,从我所看到的,这是它调用法庭预订的JavaScript脚本:
function load_js(url) {
var e = document.createElement("script");
e.src = url;
e.type = "text/javascript";
if (document.getElementsByTagName("head")[0].lastChild.src == e.src) {
document.getElementsByTagName("head")[0].replaceChild(e, document.getElementsByTagName("head")[0].lastChild);
}
else {
document.getElementsByTagName("head")[0].appendChild(e);
}
}
onload = function () {
setInterval("load_js('/js/bookings_reload.js.php')", 30000);
};
我怎么能在Flutter中复制这个?我可以抓取HTML并解析它以创建HTML文档,但由于Flutter不允许使用dart:html库,因此我无法创建ScriptElement来复制JavaScript脚本。 Flutter有替代品吗?
到目前为止,这是我的Dart功能:
var httpClient = createHttpClient();
getData() async {
// Send POST request to get authorized cookie
var response = await httpClient.post('http://bookings.squashgym.co.nz/login',
body: {'username': username, 'password': password});
// Send get request with authenticated cookie to get bookings
var courts = await httpClient.get('http://bookings.squashgym.co.nz/booking-sheet',
headers: {'cookie': response.headers['set-cookie']});
Document data = parse(courts.body);
httpClient.close();
}
谢谢!
答案 0 :(得分:0)
我同意使用 WebView 加载所需的 URL。以下是使用 webview_flutter 的 WebView 的示例实现。
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'dart:async';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final Completer<WebViewController> _controller =
Completer<WebViewController>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: WebView(
initialUrl: "https://flutter.dev/",
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
javascriptMode: JavascriptMode.unrestricted,
),
);
}
}
这是它的样子:
当页面呈现时,您将能够从 WebView 获取 DOM。还有一个从 WebView 获取 DOM 的可用示例。检查它here。