BrowseCrawler — Offline crawling of entire trees
Overview
IDE / HMI When working online, it is often necessary to load the AddressSpace subtree locally so that subsequent node searches do not require additional requests Browse RPC.BrowseCrawler Use a BFS queue to traverse the subtree, with double protection (max_depth + max_nodes) to prevent errors.
API
| Members | Category | Reading and Writing | Note |
|---|---|---|---|
| BrowseCrawler(ua, max_depth, max_nodes, node_class_filter) | Structure | — | Building a Web Crawler |
| await crawler.crawl(root_node_id, progress_callback) | Methods | Read | Asynchronous BFS, Returns CrawlResult |
| CrawlNode.node_id / display_name / browse_name / node_class / parent_node_id | Properties | Read | Description of a Single Node |
| CrawlResult.all_nodes | Properties | Read | Flat Node List (List[CrawlNode], BFS Order) |
| CrawlResult.children_by_parent | Properties | Read | Parent NodeId → Child NodeId List (Dict[str, List[str]], containing only parents that actually have children) |
| CrawlResult.crawled_at | Properties | Read | Start time UTC of the crawl (datetime) |
| CrawlResult.elapsed | Properties | Read | Total time (timedelta) |
class BrowseCrawler:
def __init__(self,
ua: "OpcUaSession",
max_depth: int = 10,
max_nodes: int = 100_000,
node_class_filter: NodeClass = NodeClass.Unspecified): ...
async def crawl(self,
root_node_id: Optional[str] = None,
progress_callback: Optional[ProgressCallback] = None) -> CrawlResult: ...
# Progress Callback Signature
ProgressCallback = Callable[[int, Optional[str]], None] # progress(count, current_nid)
| Parameters | Default | Note |
|---|---|---|
| ua | — | Connected OpcUaSession; Pass; Throw None ValueError |
| max_depth | 10 | Maximum Recursion Depth, <= 0 Skip ValueError |
| max_nodes | 100_000 | Maximum number of nodes, <= 0 Discard ValueError |
| node_class_filter | NodeClass.Unspecified | Write only to the NodeClass specified nodes; Unspecified = all.Filtering does not affect the traversal — BFS It will still traverse all hierarchical child nodes, but will not write the results. |
| root_node_id | None | Starting point NodeId; if empty, automatically use ( wkn.OBJECTS_FOLDER i=85) |
| progress_callback | None | progress(count, current_nid); Report once for every 100 nodes written, and report one final time when the crawl is complete progress(总数, None). Any exceptions thrown by the callback will be suppressed and will not affect the crawl. |
Returns CrawlResult.CrawlNode Fields: node_id / display_name / browse_name / node_class / parent_node_id (the last two may be None).
Code Example
import asyncio
from darra_opcua import DarraOpcUa, BrowseCrawler, NodeClass, wkn # Module Name darra_opcua
async def main():
with DarraOpcUa("opc.tcp://localhost:4840") as ua:
ua.connect()
# 1) Climb the entire tree ObjectsFolder
crawler = BrowseCrawler(ua, max_depth=8, max_nodes=50_000)
def on_progress(count, current_nid):
print(f"\r已抓 {count} 个, 当前 {current_nid}", end="")
result = await crawler.crawl(wkn.OBJECTS_FOLDER, progress_callback=on_progress)
print(f"\n共 {len(result.all_nodes)} 节点, 耗时 {result.elapsed.total_seconds():.1f}s")
print(f"开始于 {result.crawled_at}")
# 2) Variable nodes only (filtering affects only writes, not traversal)
c2 = BrowseCrawler(ua, node_class_filter=NodeClass.Variable)
r2 = await c2.crawl("ns=2;s=Boilers")
for n in r2.all_nodes:
print(f" {n.browse_name} ({n.node_id})")
# 3) Parent-Child View
for parent, kids in result.children_by_parent.items():
print(f"{parent} -> {len(kids)} 个子节点")
asyncio.run(main())
Implementation Constraints
- No cancellation mechanism —
crawl()It has onlyroot_node_id/progress_callbacktwo parameters and no cancellation input parameters. Once the crawl starts, it willawaitrun until it reaches a natural end (after traversing all elements / encounteringmax_depth/ encounteringmax_nodes).To “cancel” the process, the caller must decide to terminate it early—returnfor example, by placingcrawlintoasyncio.create_task, and then discarding the task when you want to stop, so that the result is no longer returnedawait; in scenarios with limited scale, simply usemax_depth/max_nodesas a fallback. - Each time the crawler runs Browse
ua.browse_safe, if a single node fails, it simply skips that node without interrupting the overall crawl. - If an exception is thrown by a progress callback, it is SDK swallowed; this does not affect the crawling process or other callbacks.
- Progress is reported only once for every 100 nodes; there is no fine-grained progress tracking in between.
- The graph allows cycles; use the "visited" set to remove
setduplicates; each duplicate is included in NodeId the result only once. - The crawler runs in a thread pool, so it does not block the caller's event loop.
Best Practices
- Limit the search to the root; do not start crawling the entire tree from
i=84the root. - Use
max_depth/max_nodesto limit the size — this is the only way to terminate the crawl early (there is no "cancel" parameter). - Crawl everything once at startup, then retrieve results from the local cache afterward.
- Use
node_class_filterto control the node type of the write result, thereby reducing memory usage.
Cross-Language Comparison
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| BrowseCrawler | BrowseCrawler | BrowseCrawler | BrowseCrawler | BrowseCrawler | DarraUa_Session_CrawlAddressSpace |
| CrawlAsync(rootNodeId, IProgress, CancellationToken) | crawl(root_node_id, progress_callback) | crawlAsync | CrawlAsync | crawl | DarraUa_Session_CrawlAddressSpace |
The entry point for C is a single function DarraUa_Session_CrawlAddressSpace(session, config, on_node, ctx), accompanied by DarraUa_CrawlerConfig(DarraUa_CrawlerConfig_Init initialization) / DarraUa_CrawlNode / DarraUa_OnCrawlNode,There is no such DarraUa_BrowseCrawler_* family; The two lines above represent the same function on the C side.
Differences in the ability to undo: C# has CrawlAsync it CancellationToken, Python has no crawl cancel parameter.。