Class: Scrapetor::Native::DocumentWrapper

Inherits:
Object
  • Object
show all
Defined in:
lib/scrapetor/native_dom.rb

Overview

Document wrapper — wraps Native::Document and provides Dom-like methods so ‘Scrapetor::Document#backing` can return one of these interchangeably with `Dom::Document`.

Defined Under Namespace

Classes: LazyIds

Constant Summary collapse

COMPILE_CACHE_CAP =

The compile cache lives on the wrapper so repeated queries (the common case in scraping pipelines, where the same set of selectors run against thousands of pages) skip the parse + native-plan build entirely. Sized to cover typical templates; untouched entries fall off the back when we exceed cap.

1024

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(native) ⇒ DocumentWrapper

Returns a new instance of DocumentWrapper.



948
949
950
951
952
953
954
955
956
957
958
959
960
# File 'lib/scrapetor/native_dom.rb', line 948

def initialize(native)
  @native = native
  # Back-pointer so Elements created from this wrapper can
  # find their way back without us threading `wrapper:` through
  # every navigation method.
  native.instance_variable_set(:@__scrapetor_wrapper, self) if native.respond_to?(:instance_variable_set)
  @dom_doc  = nil
  @dom_mode = false
  @compile_cache = {}
  # Path cache keyed by native node id. Stable until the tree
  # mutates (dom-mode flip clears it).
  @path_cache = {}
end

Instance Attribute Details

#nativeObject (readonly)

Returns the value of attribute native.



939
940
941
# File 'lib/scrapetor/native_dom.rb', line 939

def native
  @native
end

Instance Method Details

#apply_transform(nodes, kind, arg) ⇒ Object



1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
# File 'lib/scrapetor/native_dom.rb', line 1370

def apply_transform(nodes, kind, arg)
  case kind
  when nil then nodes
  when :text, :text_approx
    nodes.map do |n|
      t = Scrapetor::TextNode.new(n.respond_to?(:text) ? n.text.to_s : n.to_s)
      t.parent_node = n if n.respond_to?(:element?) && n.element?
      t
    end
  when :attr
    nodes.map do |n|
      v = n.respond_to?(:[]) ? n[arg] : nil
      next nil if v.nil?
      t = Scrapetor::TextNode.new(v)
      t.parent_node = n if n.respond_to?(:element?) && n.element?
      t
    end
  when :direct_text
    nodes.map do |n|
      t = Scrapetor::TextNode.new(direct_text_of_any(n))
      t.parent_node = n if n.respond_to?(:element?) && n.element?
      t
    end
  when :direct_attr
    out = []
    nodes.each do |n|
      v = n.respond_to?(:[]) ? n[arg] : nil
      next if v.nil?
      t = Scrapetor::TextNode.new(v)
      t.parent_node = n if n.respond_to?(:element?) && n.element?
      out << t
    end
    out
  end
end

#at_css(selector) ⇒ Object Also known as: at



1083
1084
1085
1086
1087
1088
1089
1090
1091
# File 'lib/scrapetor/native_dom.rb', line 1083

def at_css(selector)
  str = selector.to_s
  stripped, kind, arg = Native.peel_pseudo_element(str)
  stripped = "*" if stripped.empty?
  nodes = css_native_or_fallback(stripped, limit_one: true)
  return nil if nodes.empty?
  return nodes.first unless kind
  apply_transform(nodes, kind, arg).first
end

#at_xpath(_expr) ⇒ Object



1164
# File 'lib/scrapetor/native_dom.rb', line 1164

def at_xpath(_expr); nil; end

#batch_css(doc, selectors) ⇒ Object

Run N selectors in ONE C call, returning an Array of results parallel to ‘selectors`. Each result is either a `LazyIds` (wrapped by Document#css as a lazy NodeSet) or an Array of strings (for `::text` / `::attr` pseudo-elements). Selectors the native engine can’t compile fall through to the per-query Ruby path; the rest amortise to one Ruby dispatch.



1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
# File 'lib/scrapetor/native_dom.rb', line 1100

def batch_css(doc, selectors)
  plans   = Array.new(selectors.size)
  kinds   = Array.new(selectors.size)
  args    = Array.new(selectors.size)
  natives = []
  native_to_orig = []
  fallback_indices = []

  selectors.each_with_index do |sel, i|
    str = sel.to_s
    stripped, kind, arg = Native.peel_pseudo_element(str)
    stripped = "*" if stripped.empty?
    kinds[i] = kind
    args[i]  = arg
    if @dom_mode || stripped.include?(",")
      fallback_indices << i
      next
    end
    plan = compiled_plan(stripped)
    if plan
      plans[i] = plan
      natives << plan
      native_to_orig << i
    else
      fallback_indices << i
    end
  end

  out = Array.new(selectors.size)

  # One C call across all native plans.
  unless natives.empty?
    id_lists = @native.batch_chain(natives, nil)
    id_lists.each_with_index do |ids, j|
      orig = native_to_orig[j]
      out[orig] = case kinds[orig]
                  when :text, :text_approx
                    wire_parent_nodes!(@native.bulk_text(ids), ids)
                  when :attr
                    wire_parent_nodes!(@native.bulk_attr(ids, args[orig]), ids)
                  else
                    LazyIds.new(self, @native, ids)
                  end
    end
  end

  # Per-selector Ruby path for the few that need it.
  fallback_indices.each do |i|
    out[i] = lazy_css(selectors[i])
  end

  # Wrap each result as Document#css would. Lazy NodeSet for
  # node-based results; pass strings through.
  out.map! do |r|
    if r.is_a?(LazyIds)
      Scrapetor::NodeSet.new(doc, r)
    else
      r
    end
  end
  out
end

#bodyObject



1181
1182
1183
# File 'lib/scrapetor/native_dom.rb', line 1181

def body
  at_css("body")
end

#build_dom_from_nativeObject

O(N nodes) tree-walk that materialises a Scrapetor::Dom mirror of the native arena. Used for the mutation fallback path so node mutations have a Ruby-side handle to operate on, without re-tokenising the source HTML.



1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
# File 'lib/scrapetor/native_dom.rb', line 1211

def build_dom_from_native
  doc = Scrapetor::Dom::Document.new
  size = @native.size
  return doc if size <= 1
  id_to_dom = Array.new(size)
  id_to_dom[0] = doc
  i = 1
  while i < size
    type = @native.node_type(i)
    # Skip removed (tombstoned via dom_node_remove). Type
    # constants: 1=element, 3=text, 8=comment, 9=doc,
    # 0xFE=REMOVED.
    if type != 1 && type != 3 && type != 8
      i += 1
      next
    end
    parent_id = @native.node_parent(i) || 0
    parent_dom = id_to_dom[parent_id] || doc
    node = case type
           when 1
             name  = @native.node_name(i)
             attrs = @native.node_attributes(i)
             Scrapetor::Dom::Element.new(name, attrs)
           when 3
             Scrapetor::Dom::Text.new(@native.node_text(i))
           when 8
             Scrapetor::Dom::Comment.new(@native.node_text(i))
           end
    parent_dom.add_child(node)
    id_to_dom[i] = node
    i += 1
  end
  doc
end

#cached_path(id) ⇒ Object



962
963
964
# File 'lib/scrapetor/native_dom.rb', line 962

def cached_path(id)
  @path_cache[id]
end

#compiled_plan(group_str) ⇒ Object

Look up (or compile) the native plan for a single selector group. ‘nil` means “this group uses a feature the native engine doesn’t accept” — callers route those to the Ruby fallback.



973
974
975
976
977
978
979
980
981
982
983
984
# File 'lib/scrapetor/native_dom.rb', line 973

def compiled_plan(group_str)
  if (entry = @compile_cache[group_str])
    return entry == false ? nil : entry
  end
  plan = Native.compile_selector_chain(group_str)
  @compile_cache.shift if @compile_cache.size >= COMPILE_CACHE_CAP
  @compile_cache[group_str] = plan.nil? ? false : plan
  if plan.nil? && ENV["SCRAP_TRACE_FALLBACK"]
    warn "[scrap-fallback] #{group_str}"
  end
  plan
end

#contentObject



998
# File 'lib/scrapetor/native_dom.rb', line 998

def content;  text; end

#css(selector) ⇒ Object



1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
# File 'lib/scrapetor/native_dom.rb', line 1064

def css(selector)
  str = selector.to_s
  stripped, kind, arg = Native.peel_pseudo_element(str)
  stripped = "*" if stripped.empty?
  if kind && !@dom_mode
    ids = native_ids(stripped)
    if ids
      return case kind
             when :text, :text_approx
               wire_parent_nodes!(@native.bulk_text(ids), ids)
             when :attr
               wire_parent_nodes!(@native.bulk_attr(ids, arg), ids)
             end
    end
  end
  nodes = css_native_or_fallback(stripped)
  apply_transform(nodes, kind, arg)
end

#direct_text_of_any(n) ⇒ Object

Direct text-node children of an element. Used at the Document/wrapper level — accepts either a native Element or a Dom-fallback node and pulls only the immediate text children.



1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
# File 'lib/scrapetor/native_dom.rb', line 1409

def direct_text_of_any(n)
  buf = +""
  if n.is_a?(Element) && !n.send(:dom_node?)
    cid = @native.node_first_child(n.id)
    while cid
      if @native.node_type(cid) == 3
        buf << @native.node_text(cid).to_s
      end
      cid = @native.node_next_sibling(cid)
    end
  elsif n.respond_to?(:children)
    n.children.each do |c|
      if c.respond_to?(:text?) && c.text?
        buf << (c.respond_to?(:text) ? c.text.to_s : c.to_s)
      elsif !c.respond_to?(:element?) || !c.element?
        buf << c.to_s
      end
    end
  end
  buf
end

#document?Boolean

Returns:

  • (Boolean)


987
# File 'lib/scrapetor/native_dom.rb', line 987

def document?; true; end

#dom_mode?Boolean

—– internals for the mutation fallback —–

Returns:

  • (Boolean)


1191
# File 'lib/scrapetor/native_dom.rb', line 1191

def dom_mode?; @dom_mode; end

#element?Boolean

Returns:

  • (Boolean)


986
# File 'lib/scrapetor/native_dom.rb', line 986

def element?; false; end

#fallback_domObject

Build (once) and return the Ruby DOM view of this document. Used by Element#css fallback when the selector exceeds the native engine’s grammar, and by Element mutations.

The previous implementation re-tokenised the entire HTML through the Ruby SAX parser — for a 400 KB page that’s 50–100 ms on the first mutating call. The native arena is already parsed; we can build the Dom tree by walking it node-by-node in O(N) instead of O(bytes). That drops to ~5–10 ms on the same page.



1203
1204
1205
# File 'lib/scrapetor/native_dom.rb', line 1203

def fallback_dom
  @dom_doc ||= build_dom_from_native
end

#headObject



1185
1186
1187
# File 'lib/scrapetor/native_dom.rb', line 1185

def head
  at_css("head")
end

#htmlObject



1177
1178
1179
# File 'lib/scrapetor/native_dom.rb', line 1177

def html
  root
end

#lazy_css(selector) ⇒ Object



1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
# File 'lib/scrapetor/native_dom.rb', line 1013

def lazy_css(selector)
  str = selector.to_s
  # Heterogeneous pseudo groups: peel each group separately and
  # concatenate. Returns a flat Array of mixed Element/TextNode
  # results — callers wrap it in NodeSet via .to_a.
  if str.include?(",") && str.include?("::") &&
     Native.heterogeneous_pseudo_groups?(str)
    return Native.split_selector_groups(str).flat_map do |g|
      r = lazy_css(g)
      r.is_a?(LazyIds) ? r.ids.map { |nid| Element.new(@native, nid, self) } : r.to_a
    end
  end
  stripped, kind, arg = Native.peel_pseudo_element(str)
  stripped = "*" if stripped.empty?
  if kind && %i[text text_approx attr].include?(kind) && !@dom_mode
    ids = native_ids(stripped)
    if ids
      return case kind
             when :text, :text_approx
               wire_parent_nodes!(@native.bulk_text(ids), ids)
             when :attr
               wire_parent_nodes!(@native.bulk_attr(ids, arg), ids)
             end
    end
  end
  if !@dom_mode && kind.nil?
    ids = native_ids(stripped)
    return LazyIds.new(self, @native, ids) if ids
  end
  nodes = css_native_or_fallback(stripped)
  apply_transform(nodes, kind, arg)
end

#locate_dom_by_native_id(native_id) ⇒ Object

Robust cross-DOM lookup. Native ids enumerate every node in the arena (text, comments, elements). Both parsers visit ELEMENT nodes in document order, so the N-th element on the native side is the N-th element on the Ruby side — even when the two parsers disagree on whitespace text nodes or implicit close-tag handling. Used as a fallback when the path-based locator can’t find a match.



1296
1297
1298
1299
1300
1301
1302
# File 'lib/scrapetor/native_dom.rb', line 1296

def locate_dom_by_native_id(native_id)
  @native_element_offset_map ||= build_native_element_offset_map
  offset = @native_element_offset_map[native_id]
  return nil if offset.nil?
  @dom_element_index ||= build_dom_element_index
  @dom_element_index[offset]
end

#locate_in_dom(path_str) ⇒ Object

Walk a ‘/tag/…/tag` path inside the lazy Dom view. Used by Element#ensure_dom! to relocate itself after promotion.



1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
# File 'lib/scrapetor/native_dom.rb', line 1260

def locate_in_dom(path_str)
  doc = fallback_dom
  parts = path_str.to_s.split("/").reject(&:empty?)
  cur = doc
  parts.each do |part|
    if (m = part.match(/\A([\w-]+)\[@id='([^']+)'\]\z/))
      tag = m[1]; id = m[2]
      found = nil
      walk_elements(doc) do |el|
        if el.name == tag && el["id"] == id
          found = el
          break
        end
      end
      return nil if found.nil?
      cur = found
    elsif (m = part.match(/\A([\w-]+)\[(\d+)\]\z/))
      tag = m[1]; idx = m[2].to_i
      children = cur.respond_to?(:children) ? cur.children : []
      same = children.select { |c| c.respond_to?(:element?) && c.element? && c.name == tag }
      return nil if same.empty? || idx < 1 || idx > same.length
      cur = same[idx - 1]
    else
      return nil
    end
  end
  cur
end

#nameObject



988
# File 'lib/scrapetor/native_dom.rb', line 988

def name; "#document"; end

#native_ids(selector_str) ⇒ Object

Run the cached plan(s) for a selector and return the raw id Array, or nil if any group needs the Ruby fallback. Used by css() to feed bulk_text / bulk_attr without intermediate Element allocations.



1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
# File 'lib/scrapetor/native_dom.rb', line 1333

def native_ids(selector_str)
  if !selector_str.include?(",")
    plan = compiled_plan(selector_str)
    return @native.run_chain(plan, nil) if plan
    expanded = Native.expand_is_groups(selector_str)
    return nil if expanded.size <= 1
    ids = []
    seen = nil
    expanded.each do |g|
      p = compiled_plan(g)
      return nil unless p
      @native.run_chain(p, nil).each do |nid|
        seen ||= {}
        next if seen[nid]
        seen[nid] = true
        ids << nid
      end
    end
    return ids
  end
  ids = []
  seen = nil
  groups = Native.split_selector_groups(selector_str)
    .flat_map { |g| Native.expand_is_groups(g) }
  groups.each do |g|
    plan = compiled_plan(g)
    return nil unless plan
    @native.run_chain(plan, nil).each do |nid|
      seen ||= {}
      next if seen[nid]
      seen[nid] = true
      ids << nid
    end
  end
  ids
end

#rootObject



990
991
992
993
# File 'lib/scrapetor/native_dom.rb', line 990

def root
  rid = @native.root_id
  Element.new(@native, rid, self)
end

#root_elementObject



995
# File 'lib/scrapetor/native_dom.rb', line 995

def root_element; root; end

#store_path(id, str) ⇒ Object



966
967
968
# File 'lib/scrapetor/native_dom.rb', line 966

def store_path(id, str)
  @path_cache[id] = str
end

#switch_to_dom!Object

Promote the document to dom-mode. After this, css() runs only against the Dom view (it is the source of truth for mutations the user has already made).



1249
1250
1251
1252
1253
1254
1255
# File 'lib/scrapetor/native_dom.rb', line 1249

def switch_to_dom!
  fallback_dom
  @dom_mode = true
  # Cached paths may not survive a mutation series; let them
  # rebuild lazily after the switch.
  @path_cache = {}
end

#textObject



997
# File 'lib/scrapetor/native_dom.rb', line 997

def text;     fallback_dom.text; end

#to_htmlObject Also known as: to_s



1172
1173
1174
# File 'lib/scrapetor/native_dom.rb', line 1172

def to_html
  @dom_mode ? @dom_doc.to_html : @native.html
end

#traverse(&block) ⇒ Object



1166
1167
1168
1169
1170
# File 'lib/scrapetor/native_dom.rb', line 1166

def traverse(&block)
  return enum_for(:traverse) unless block_given?
  root.traverse(&block)
  self
end

#wire_parent_nodes!(values, ids) ⇒ Object

Set each TextNode’s parent_node to the matching element it came from. Production parser code (Google Light’s organic results, Yahoo’s knowledge graph) chains ‘result.parent.css(…)` to walk into siblings of a `::text` match — without a parent ref the `.parent` returns nil and the next call crashes.



1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
# File 'lib/scrapetor/native_dom.rb', line 1051

def wire_parent_nodes!(values, ids)
  i = 0
  n = values.length
  while i < n
    v = values[i]
    if v.is_a?(Scrapetor::TextNode)
      v.parent_node = Element.new(@native, ids[i], self)
    end
    i += 1
  end
  values
end

#xpath(_expr) ⇒ Object



1163
# File 'lib/scrapetor/native_dom.rb', line 1163

def xpath(_expr); []; end