一個受 Python 的 Beautiful Soup 4 啟發的原生 Dart HTML 解析庫。它透過簡單直覺的 API,實現對 HTML 文件的輕鬆導航、搜尋與修改。非常適合從 HTML 內容中提取資料,或在 Flutter 與其他 Dart 應用程式中操作 DOM 結構。此套件支援所有主要平台,包含 Web、行動裝置與桌面端。
適用情境
Web 抓取 HTML 內容
解析動態HTML回應
從網頁中提取結構化數據
在渲染之前修改 HTML
建構靜態網站產生器
主要特色
直覺式的 CSS 與標籤選擇器
輕鬆導航父/子關係
支援文字與屬性提取
靈活的搜尋方法(find、findAll)
跨平台相容性
適合對象
在Flutter應用中解析HTML的開發者
從網絡來源提取資料
需要DOM操作的工具
靜態網站產生工作流程
使用建議
未針對大型 HTML 檔案進行優化
僅限解析,不支援渲染HTML
需要仔細處理格式錯誤的輸入
不支援內建 JavaScript 執行
原始 README
以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。
Beautiful Soup Dart
Dart native package inspired by Beautiful Soup 4 Python library. Provides easy ways of navigating, searching, and
modifying the HTML tree.
Usage
A simple usage example:
import'package:beautiful_soup_dart/beautiful_soup.dart';
/// 1. parse a document StringBeautifulSoup bs = BeautifulSoup(html_doc_string);
// use BeautifulSoup.fragment(html_doc_string) if you parse a part of html/// 2. navigate quickly to any element
bs.body!.a!; // navigate quickly with tags, use outerHtml or toString to get outer html
bs.find('p', class_: 'story'); // finds first element with html tag "p" and which has "class" attribute with value "story"
bs.findAll('a', attrs: {'class': true}); // finds all elements with html tag "a" and which have defined "class" attribute with whatever value
bs.find('', selector: '#link1'); // find with custom CSS selector (other parameters are ignored)
bs.find('*', id: 'link1'); // any element with id "link1"
bs.find('*', regex: r'^b'); // find any element which tag starts with "b", for example: body, b, ...
bs.find('p', string: r'^Article #\d*'); // find "p" element which text starts with "Article #[number]"
bs.find('a', attrs: {'href': 'http://example.com/elsie'}); // finds by "href" attribute/// 3. perform any other actions for the navigated elementBs4Element bs4 = bs.body!.p!; // navigate quickly with tags
bs4.name; // get tag name
bs4.string; // get text
bs4.toString(); // get String representation of this element, same as outerHtml
bs4.innerHtml; // get html elements inside the element
bs4.className; // get class attribute value
bs4['class']; // get class attribute value
bs4['class'] = 'board'; // change class attribute value to 'board'
bs4.children; // get all element's children elements
bs4.replaceWith(otherBs4Element); // replace with other element
... and many more