一个轻量级的 Flutter/Dart 包,用于通过抓取标签及其属性来提取 HTML 内容,并将其转换为结构化的 Dart 列表和映射。非常适合解析静态网页或从 HTML 源获取数据,而无需进行完整的 DOM 操作。它支持多种平台,包括移动设备、Web 和桌面端,使其成为需要从 HTML 响应中提取结构化数据的跨平台应用程序的多功能选择。
适合场景
从静态网页中提取数据
解析 HTML 表格和列表
从网页内容中抓取元数据
从HTML源填充本地数据
构建简单的网络爬虫
主要特点
用于HTML标签提取的简单API
支持属性和文本内容的检索
将抓取的数据转换为 Dart 列表和映射
跨平台兼容性
轻量且易于集成
适合对象
开发数据获取应用的开发者
需要HTML解析但不使用重型框架的项目
原型设计网络爬虫功能
需要最少服务器端处理的应用程序
使用建议
不适用于动态 JavaScript 渲染的内容
需要有效的HTML输入
可能无法优雅地处理格式错误的HTML
仅限静态页面抓取
依赖外部HTML源的可靠性
原始 README
以下为关联源码仓库的 README 原文快照,最新内容请访问源码仓库。
A Simple Web Scraper for Dart & Flutter
A very basic web scraper implementation to scrap html elements from a web page.
Pull requests are most welcome.
Getting Started
In your pubspec.yaml root add:
dependencies:web_scraper:
then,
import'package:web_scraper/web_scraper.dart';
Note that as of version 0.0.6, the project supports not only Flutter projects, but also Dart projects.
Implementation
final webScraper = WebScraper('https://webscraper.io');
if (await webScraper.loadWebPage('/test-sites/e-commerce/allinone')) {
List<Map<String, dynamic>> elements = webScraper.getElement('div.thumbnail > div.caption', ['h4']);
print(elements);
}
Loads the webpage into response object and then parse it into the document object
String route
Future <bool>
loadFromURL
Loads the webpage from provided URL into response object and then parse it into the document object
String page
Future <bool>
loadFromString
Loads the webpage from a String (usually stored by the getPageContent method) into response object and then parse it into the document object. This operation is completely synchronous and exists as a helper method to perform compute() flutter operations and avoid jank
String responseBodyAsString
Future <bool>
getPageContent
Returns webpage's html in string format
Void
String body
getElement
Returns List of elements found at specified address
String address, List <String> attributes
List <Map<String, dynamic>>
getElementTitle
Returns List of element titles found at specified address
String address
List <String>
getElementAttribute
Returns List of elements single attribute found at specified address (if you wish to get multiple attributes at once, please use getElement instead)
String address, List <String> attributes
List <String>
getAllScripts
Returns the list of all data enclosed in script tags of the document
Void
List <String>
getScriptVariables
Returns Map between given variable names and list of their occurence in the script tags
List <String> variableNames
Map <String, dynamic>
Contributing
Please branch from develop to implement bug fix/new feature.
Ensure that code is formatted according to base dart rules & using the latest stable version of dart.
Open a PR with develop as the PR target with a clear description.