Skip to main content

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​

MembersCategoryReading and WritingNote
BrowseCrawler(ua, max_depth, max_nodes, node_class_filter)Structure—Building a Web Crawler
await crawler.crawl(root_node_id, progress_callback)MethodsReadAsynchronous BFS, Returns CrawlResult
CrawlNode.node_id / display_name / browse_name / node_class / parent_node_idPropertiesReadDescription of a Single Node
CrawlResult.all_nodesPropertiesReadFlat Node List (List[CrawlNode], BFS Order)
CrawlResult.children_by_parentPropertiesReadParent NodeId → Child NodeId List (Dict[str, List[str]], containing only parents that actually have children)
CrawlResult.crawled_atPropertiesReadStart time UTC of the crawl (datetime)
CrawlResult.elapsedPropertiesReadTotal 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)
ParametersDefaultNote
ua—Connected OpcUaSession; Pass; Throw None ValueError
max_depth10Maximum Recursion Depth, <= 0 Skip ValueError
max_nodes100_000Maximum number of nodes, <= 0 Discard ValueError
node_class_filterNodeClass.UnspecifiedWrite 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_idNoneStarting point NodeId; if empty, automatically use ( wkn.OBJECTS_FOLDER i=85)
progress_callbackNoneprogress(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 only root_node_id / progress_callback two parameters and no cancellation input parameters. Once the crawl starts, it will await run until it reaches a natural end (after traversing all elements / encountering max_depth / encountering max_nodes).To “cancel” the process, the caller must decide to terminate it early— return for example, by placing crawl into asyncio.create_task, and then discarding the task when you want to stop, so that the result is no longer returned await; in scenarios with limited scale, simply use max_depth / max_nodes as 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 set duplicates; 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=84 the root.
  • Use max_depth / max_nodes to 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_filter to control the node type of the write result, thereby reducing memory usage.

Cross-Language Comparison​

C#PythonJavaC++RustC
BrowseCrawlerBrowseCrawlerBrowseCrawlerBrowseCrawlerBrowseCrawlerDarraUa_Session_CrawlAddressSpace
CrawlAsync(rootNodeId, IProgress, CancellationToken)crawl(root_node_id, progress_callback)crawlAsyncCrawlAsynccrawlDarraUa_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.。

Next Step​