Class: Puppeteer::ElementHandle
- Inherits:
-
JSHandle
- Object
- JSHandle
- Puppeteer::ElementHandle
show all
- Includes:
- DebugPrint, IfPresent
- Defined in:
- lib/puppeteer/element_handle.rb,
lib/puppeteer/element_handle/point.rb,
lib/puppeteer/element_handle/offset.rb,
lib/puppeteer/element_handle/box_model.rb,
lib/puppeteer/element_handle/bounding_box.rb
Defined Under Namespace
Classes: BoundingBox, BoxModel, DragInterceptionNotEnabledError, ElementNotClickableError, ElementNotFoundError, ElementNotVisibleError, Offset, Point, ScrollIntoViewError
Instance Attribute Summary
Attributes inherited from JSHandle
#context, #remote_object
Instance Method Summary
collapse
-
#as_element ⇒ Object
-
#bounding_box ⇒ BoundingBox|nil
-
#box_model ⇒ BoxModel|nil
-
#click(delay: nil, button: nil, click_count: nil, offset: nil) ⇒ Object
-
#clickable_point(offset = nil) ⇒ Object
-
#content_frame ⇒ Object
-
#drag(x:, y:) ⇒ Object
-
#drag_and_drop(target, delay: nil) ⇒ Object
-
#drag_enter(data) ⇒ Object
-
#drag_over(data) ⇒ Object
-
#drop(data) ⇒ Object
-
#eval_on_selector(selector, page_function, *args) ⇒ Object
(also: #Seval)
-
#eval_on_selector_all(selector, page_function, *args) ⇒ Object
(also: #SSeval)
‘$$eval()` in JavaScript.
-
#focus ⇒ Object
-
#hover ⇒ Object
-
#initialize(context:, client:, remote_object:, frame:, page:, frame_manager:) ⇒ ElementHandle
constructor
A new instance of ElementHandle.
-
#inspect ⇒ Object
-
#intersecting_viewport?(threshold: nil) ⇒ Boolean
in JS, #isIntersectingViewport.
-
#press(key, delay: nil, text: nil) ⇒ Object
-
#query_ax_tree(accessible_name: nil, role: nil) ⇒ Object
used in AriaQueryHandler.
-
#query_selector(selector) ⇒ Object
(also: #S)
-
#query_selector_all(selector) ⇒ Object
(also: #SS)
-
#screenshot(type: nil, path: nil, full_page: nil, clip: nil, quality: nil, omit_background: nil, encoding: nil) ⇒ Object
-
#scroll_into_view_if_needed ⇒ Object
-
#select(*values) ⇒ Array<String>
-
#Sx(expression) ⇒ Array<ElementHandle>
-
#tap(&block) ⇒ Object
-
#type_text(text, delay: nil) ⇒ Object
-
#upload_file(*file_paths) ⇒ Object
-
#wait_for_selector(selector, visible: nil, hidden: nil, timeout: nil) ⇒ Object
Wait for the ‘selector` to appear within the element.
Methods included from IfPresent
#if_present
Methods included from DebugPrint
#debug_print, #debug_puts
Methods inherited from JSHandle
#[], create, #dispose, #disposed?, #evaluate, #evaluate_handle, #execution_context, #json_value, #properties, #property, #to_s
Constructor Details
#initialize(context:, client:, remote_object:, frame:, page:, frame_manager:) ⇒ ElementHandle
Returns a new instance of ElementHandle.
17
18
19
20
21
22
23
|
# File 'lib/puppeteer/element_handle.rb', line 17
def initialize(context:, client:, remote_object:, frame:, page:, frame_manager:)
super(context: context, client: client, remote_object: remote_object)
@frame = frame
@page = page
@frame_manager = frame_manager
@disposed = false
end
|
Instance Method Details
#as_element ⇒ Object
79
80
81
|
# File 'lib/puppeteer/element_handle.rb', line 79
def as_element
self
end
|
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
|
# File 'lib/puppeteer/element_handle.rb', line 401
def bounding_box
if_present(box_model) do |result_model|
offset = oopif_offsets(@frame)
quads = result_model.border
x = quads.map(&:x).min
y = quads.map(&:y).min
BoundingBox.new(
x: x + offset.x,
y: y + offset.y,
width: quads.map(&:x).max - x,
height: quads.map(&:y).max - y,
)
end
end
|
#box_model ⇒ BoxModel|nil
418
419
420
421
422
|
# File 'lib/puppeteer/element_handle.rb', line 418
def box_model
if_present(@remote_object.box_model(@client)) do |result|
BoxModel.new(result['model'], offset: oopif_offsets(@frame))
end
end
|
#click(delay: nil, button: nil, click_count: nil, offset: nil) ⇒ Object
256
257
258
259
260
|
# File 'lib/puppeteer/element_handle.rb', line 256
def click(delay: nil, button: nil, click_count: nil, offset: nil)
scroll_into_view_if_needed
point = clickable_point(offset)
@page.mouse.click(point.x, point.y, delay: delay, button: button, click_count: click_count)
end
|
#clickable_point(offset = nil) ⇒ Object
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
|
# File 'lib/puppeteer/element_handle.rb', line 170
def clickable_point(offset = nil)
offset_param = Offset.from(offset)
result =
begin
@remote_object.content_quads(@client)
rescue => err
debug_puts(err)
nil
end
if !result || result["quads"].empty?
raise ElementNotVisibleError.new
end
layout_metrics = @page.client.send_message('Page.getLayoutMetrics')
if result.empty? || result["quads"].empty?
raise ElementNotClickableError.new
end
layout_viewport = layout_metrics["cssLayoutViewport"] || layout_metrics["layoutViewport"]
client_width = layout_viewport["clientWidth"]
client_height = layout_viewport["clientHeight"]
oopif_offset = oopif_offsets(@frame)
quads = result["quads"].
map { |quad| from_protocol_quad(quad) }.
map { |quad| apply_offsets_to_quad(quad, oopif_offset) }.
map { |quad| intersect_quad_with_viewport(quad, client_width, client_height) }.
select { |quad| compute_quad_area(quad) > 1 }
if quads.empty?
raise ElementNotVisibleError.new
end
if offset_param
quad = quads.first
min_x = quad.map(&:x).min
min_y = quad.map(&:y).min
if min_x && min_y
return Point.new(
x: min_x + offset_param.x,
y: min_y + offset_param.y,
)
end
end
quads.first.reduce(:+) / 4
end
|
#content_frame ⇒ Object
83
84
85
86
87
88
89
90
91
|
# File 'lib/puppeteer/element_handle.rb', line 83
def content_frame
node_info = @remote_object.node_info(@client)
frame_id = node_info['node']['frameId']
if frame_id.is_a?(String)
@frame_manager.frame(frame_id)
else
nil
end
end
|
#drag(x:, y:) ⇒ Object
270
271
272
273
274
275
276
277
|
# File 'lib/puppeteer/element_handle.rb', line 270
def drag(x:, y:)
unless @page.drag_interception_enabled?
raise DragInterceptionNotEnabledError.new
end
scroll_into_view_if_needed
start = clickable_point
@page.mouse.drag(start, Point.new(x: x, y: y))
end
|
#drag_and_drop(target, delay: nil) ⇒ Object
298
299
300
301
302
303
|
# File 'lib/puppeteer/element_handle.rb', line 298
def drag_and_drop(target, delay: nil)
scroll_into_view_if_needed
start_point = clickable_point
target_point = target.clickable_point
@page.mouse.drag_and_drop(start_point, target_point, delay: delay)
end
|
#drag_enter(data) ⇒ Object
279
280
281
282
283
|
# File 'lib/puppeteer/element_handle.rb', line 279
def drag_enter(data)
scroll_into_view_if_needed
target = clickable_point
@page.mouse.drag_enter(target, data)
end
|
#drag_over(data) ⇒ Object
285
286
287
288
289
|
# File 'lib/puppeteer/element_handle.rb', line 285
def drag_over(data)
scroll_into_view_if_needed
target = clickable_point
@page.mouse.drag_over(target, data)
end
|
#drop(data) ⇒ Object
291
292
293
294
295
|
# File 'lib/puppeteer/element_handle.rb', line 291
def drop(data)
scroll_into_view_if_needed
target = clickable_point
@page.mouse.drop(target, data)
end
|
#eval_on_selector(selector, page_function, *args) ⇒ Object
Also known as:
Seval
503
504
505
506
507
508
509
510
511
512
|
# File 'lib/puppeteer/element_handle.rb', line 503
def eval_on_selector(selector, page_function, *args)
element_handle = query_selector(selector)
unless element_handle
raise ElementNotFoundError.new(selector)
end
result = element_handle.evaluate(page_function, *args)
element_handle.dispose
result
end
|
#eval_on_selector_all(selector, page_function, *args) ⇒ Object
Also known as:
SSeval
‘$$eval()` in JavaScript.
521
522
523
524
525
526
527
|
# File 'lib/puppeteer/element_handle.rb', line 521
def eval_on_selector_all(selector, page_function, *args)
handles = query_handler_manager.detect_query_handler(selector).query_all_array(self)
result = handles.evaluate(page_function, *args)
handles.dispose
result
end
|
#focus ⇒ Object
375
376
377
|
# File 'lib/puppeteer/element_handle.rb', line 375
def focus
evaluate('element => element.focus()')
end
|
#hover ⇒ Object
246
247
248
249
250
|
# File 'lib/puppeteer/element_handle.rb', line 246
def hover
scroll_into_view_if_needed
point = clickable_point
@page.mouse.move(point.x, point.y)
end
|
#inspect ⇒ Object
25
26
27
28
29
30
31
|
# File 'lib/puppeteer/element_handle.rb', line 25
def inspect
values = %i[context remote_object page disposed].map do |sym|
value = instance_variable_get(:"@#{sym}")
"@#{sym}=#{value}"
end
"#<Puppeteer::ElementHandle #{values.join(' ')}>"
end
|
#intersecting_viewport?(threshold: nil) ⇒ Boolean
in JS, #isIntersectingViewport.
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
|
# File 'lib/puppeteer/element_handle.rb', line 558
def intersecting_viewport?(threshold: nil)
option_threshold = threshold || 0
js = <<~JAVASCRIPT
async (element, threshold) => {
const visibleRatio = await new Promise(resolve => {
const observer = new IntersectionObserver(entries => {
resolve(entries[0].intersectionRatio);
observer.disconnect();
});
observer.observe(element);
});
if (threshold === 1) return visibleRatio === 1;
else return visibleRatio > threshold;
}
JAVASCRIPT
evaluate(js, option_threshold)
end
|
#press(key, delay: nil, text: nil) ⇒ Object
393
394
395
396
|
# File 'lib/puppeteer/element_handle.rb', line 393
def press(key, delay: nil, text: nil)
focus
@page.keyboard.press(key, delay: delay, text: text)
end
|
#query_ax_tree(accessible_name: nil, role: nil) ⇒ Object
585
586
587
588
|
# File 'lib/puppeteer/element_handle.rb', line 585
def query_ax_tree(accessible_name: nil, role: nil)
@remote_object.query_ax_tree(@client,
accessible_name: accessible_name, role: role)
end
|
#query_selector(selector) ⇒ Object
Also known as:
S
481
482
483
|
# File 'lib/puppeteer/element_handle.rb', line 481
def query_selector(selector)
query_handler_manager.detect_query_handler(selector).query_one(self)
end
|
#query_selector_all(selector) ⇒ Object
Also known as:
SS
488
489
490
|
# File 'lib/puppeteer/element_handle.rb', line 488
def query_selector_all(selector)
query_handler_manager.detect_query_handler(selector).query_all(self)
end
|
#screenshot(type: nil, path: nil, full_page: nil, clip: nil, quality: nil, omit_background: nil, encoding: nil) ⇒ Object
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
|
# File 'lib/puppeteer/element_handle.rb', line 424
def screenshot(type: nil, path: nil, full_page: nil, clip: nil, quality: nil, omit_background: nil, encoding: nil)
needs_viewport_reset = false
box = bounding_box
unless box
raise ElementNotVisibleError.new
end
viewport = @page.viewport
if viewport && (box.width > viewport.width || box.height > viewport.height)
new_viewport = viewport.merge(
width: [viewport.width, box.width.to_i].min,
height: [viewport.height, box.height.to_i].min,
)
@page.viewport = new_viewport
needs_viewport_reset = true
end
scroll_into_view_if_needed
box = bounding_box
unless box
raise ElementNotVisibleError.new
end
if box.width == 0
raise 'Node has 0 width.'
end
if box.height == 0
raise 'Node has 0 height.'
end
layout_metrics = @client.send_message('Page.getLayoutMetrics')
page_x = layout_metrics["layoutViewport"]["pageX"]
page_y = layout_metrics["layoutViewport"]["pageY"]
if clip.nil?
clip = {
x: page_x + box.x,
y: page_y + box.y,
width: box.width,
height: box.height,
}
end
@page.screenshot(type: type, path: path, full_page: full_page, clip: clip, quality: quality, omit_background: omit_background, encoding: encoding)
ensure
if needs_viewport_reset
@page.viewport = viewport
end
end
|
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
|
# File 'lib/puppeteer/element_handle.rb', line 95
def scroll_into_view_if_needed
js = <<~JAVASCRIPT
async(element, pageJavascriptEnabled) => {
if (!element.isConnected)
return 'Node is detached from document';
if (element.nodeType !== Node.ELEMENT_NODE)
return 'Node is not of type HTMLElement';
if (element.scrollIntoViewIfNeeded) {
element.scrollIntoViewIfNeeded({block: 'center', inline: 'center', behavior: 'instant'});
} else {
// force-scroll if page's javascript is disabled.
if (!pageJavascriptEnabled) {
element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'});
return false;
}
const visibleRatio = await new Promise(resolve => {
const observer = new IntersectionObserver(entries => {
resolve(entries[0].intersectionRatio);
observer.disconnect();
});
observer.observe(element);
});
if (visibleRatio !== 1.0)
element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'});
}
return false;
}
JAVASCRIPT
error = evaluate(js, @page.javascript_enabled) if error
raise ScrollIntoViewError.new(error)
end
sleep 0.16
end
|
#select(*values) ⇒ Array<String>
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
|
# File 'lib/puppeteer/element_handle.rb', line 306
def select(*values)
if nonstring = values.find { |value| !value.is_a?(String) }
raise ArgumentError.new("Values must be strings. Found value \"#{nonstring}\" of type \"#{nonstring.class}\"")
end
fn = <<~JAVASCRIPT
(element, values) => {
if (element.nodeName.toLowerCase() !== 'select') {
throw new Error('Element is not a <select> element.');
}
const options = Array.from(element.options);
element.value = undefined;
for (const option of options) {
option.selected = values.includes(option.value);
if (option.selected && !element.multiple) {
break;
}
}
element.dispatchEvent(new Event('input', { bubbles: true }));
element.dispatchEvent(new Event('change', { bubbles: true }));
return options.filter(option => option.selected).map(option => option.value);
}
JAVASCRIPT
evaluate(fn, values)
end
|
‘$x()` in JavaScript. $ is not allowed to use as a method name in Ruby.
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
|
# File 'lib/puppeteer/element_handle.rb', line 535
def Sx(expression)
fn = <<~JAVASCRIPT
(element, expression) => {
const document = element.ownerDocument || element;
const iterator = document.evaluate(expression, element, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);
const array = [];
let item;
while ((item = iterator.iterateNext()))
array.push(item);
return array;
}
JAVASCRIPT
handles = evaluate_handle(fn, expression)
properties = handles.properties
handles.dispose
properties.values.map(&:as_element).compact
end
|
#tap(&block) ⇒ Object
365
366
367
368
369
370
371
|
# File 'lib/puppeteer/element_handle.rb', line 365
def tap(&block)
return super(&block) if block
scroll_into_view_if_needed
point = clickable_point
@page.touchscreen.tap(point.x, point.y)
end
|
#type_text(text, delay: nil) ⇒ Object
383
384
385
386
|
# File 'lib/puppeteer/element_handle.rb', line 383
def type_text(text, delay: nil)
focus
@page.keyboard.type_text(text, delay: delay)
end
|
#upload_file(*file_paths) ⇒ Object
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
|
# File 'lib/puppeteer/element_handle.rb', line 334
def upload_file(*file_paths)
is_multiple = evaluate("el => el.multiple")
if !is_multiple && file_paths.length >= 2
raise ArgumentError.new('Multiple file uploads only work with <input type=file multiple>')
end
if error_path = file_paths.find { |file_path| !File.exist?(file_path) }
raise ArgumentError.new("#{error_path} does not exist or is not readable")
end
backend_node_id = @remote_object.node_info(@client)["node"]["backendNodeId"]
if file_paths.empty?
fn = <<~JAVASCRIPT
(element) => {
element.files = new DataTransfer().files;
// Dispatch events for this case because it should behave akin to a user action.
element.dispatchEvent(new Event('input', { bubbles: true }));
element.dispatchEvent(new Event('change', { bubbles: true }));
}
JAVASCRIPT
await evaluate(fn)
else
@remote_object.set_file_input_files(@client, file_paths.map { |path| File.expand_path(path) }, backend_node_id)
end
end
|
#wait_for_selector(selector, visible: nil, hidden: nil, timeout: nil) ⇒ Object
Wait for the ‘selector` to appear within the element. If at the moment of calling the method the `selector` already exists, the method will return immediately. If the `selector` doesn’t appear after the ‘timeout` milliseconds of waiting, the function will throw.
This method does not work across navigations or if the element is detached from DOM.
developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector of an element to wait for is added to DOM. Resolves to ‘null` if waiting for hidden: `true` and selector is not found in DOM. The optional parameters in `options` are:
visible, i.e. to not have ‘display: none` or `visibility: hidden` CSS properties. Defaults to `false`.
i.e. have ‘display: none` or `visibility: hidden` CSS properties. Defaults to `false`.
(30 seconds). Pass ‘0` to disable timeout. The default value can be changed by using the Page.setDefaultTimeout method.
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
# File 'lib/puppeteer/element_handle.rb', line 62
def wait_for_selector(selector, visible: nil, hidden: nil, timeout: nil)
frame = @context.frame
secondary_world = frame.secondary_world
adopted_root = secondary_world.execution_context.adopt_element_handle(self)
handle = secondary_world.wait_for_selector(selector, visible: visible, hidden: hidden, timeout: timeout, root: adopted_root)
adopted_root.dispose
return nil unless handle
main_world = frame.main_world
result = main_world.execution_context.adopt_element_handle(handle)
handle.dispose
result
end
|