1
0

WebElement.pm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. package Selenium::Remote::WebElement;
  2. # ABSTRACT: Representation of an HTML Element used by Selenium Remote Driver
  3. use strict;
  4. use warnings;
  5. use Moo;
  6. use Carp qw(carp croak);
  7. =head1 DESCRIPTION
  8. Selenium Webdriver represents all the HTML elements as WebElements.
  9. This module provides a mechanism to represent them as objects &
  10. perform various actions on the related elements. This module should
  11. not be instantiated directly by the end user. Selenium::Remote::Driver
  12. instantiates this module when required. Typically, the find_element
  13. method in Selenium::Remote::Driver returns this object on which
  14. various element related operations can be carried out.
  15. What is probably most useful on this page is the list of methods below
  16. that you can perform on an element once you've found one and S::R::D
  17. has made an instance of this for you.
  18. =head1 CONSTRUCTOR
  19. =head2 new
  20. =over 4
  21. =item B<id>
  22. Required: Pass in a string representing the ID of the object. The
  23. string should be obtained from the response object of making one of
  24. the C<find_element> calls from L<Selenium::Remote::Driver>.
  25. The attribute is also set up to handle spec compliant element response
  26. objects via its `coerce` such that any of the following will work and
  27. are all equivalent:
  28. my $old_elem = Selenium::Remote::WebElement->new(
  29. id => 1,
  30. driver => $driver
  31. );
  32. my $new_remote_elem = Selenium::Remote::WebElement->new(
  33. id => { ELEMENT => 1 },
  34. driver => $driver
  35. );
  36. my $new_spec_elem = Selenium::Remote::WebElement->new(
  37. id => { 'element-6066-11e4-a52e-4f735466cecf' => 1 },
  38. driver => $driver
  39. );
  40. and then after instantiation, all three would give the following for
  41. `id`:
  42. print $elem->id; # prints 1
  43. =item B<driver>
  44. Required: Pass in a Selenium::Remote::Driver instance or one of its
  45. subclasses. The WebElement needs the appropriate Driver session to
  46. execute its commands properly.
  47. =back
  48. For typical usage of S::R::D and this module, none of this
  49. matters and it should Just Work without you having to worry about it
  50. at all. For further reading, the L<W3C
  51. spec|https://www.w3.org/TR/webdriver/#elements> strictly dictates the
  52. exact behavior.
  53. =cut
  54. has 'id' => (
  55. is => 'ro',
  56. required => 1,
  57. coerce => sub {
  58. my ($value) = @_;
  59. if (ref($value) eq 'HASH') {
  60. if (exists $value->{ELEMENT}) {
  61. # The JSONWireProtocol web element object looks like
  62. #
  63. # { "ELEMENT": $INTEGER_ID }
  64. return $value->{ELEMENT};
  65. }
  66. elsif (exists $value->{'element-6066-11e4-a52e-4f735466cecf'}) {
  67. # but the WebDriver spec web element uses a magic
  68. # string. See the spec for more information:
  69. #
  70. # https://www.w3.org/TR/webdriver/#elements
  71. return $value->{'element-6066-11e4-a52e-4f735466cecf'};
  72. }
  73. else {
  74. croak 'When passing in an object to the WebElement id attribute, it must have at least one of the ELEMENT or element-6066-11e4-a52e-4f735466cecf keys.';
  75. }
  76. }
  77. else {
  78. return $value;
  79. }
  80. }
  81. );
  82. has 'driver' => (
  83. is => 'ro',
  84. required => 1,
  85. handles => [qw(_execute_command)],
  86. );
  87. =head1 FUNCTIONS
  88. =head2 click
  89. Description:
  90. Click the element.
  91. Usage:
  92. $elem->click();
  93. =cut
  94. sub click {
  95. my ($self) = @_;
  96. my $res = { 'command' => 'clickElement', 'id' => $self->id };
  97. return $self->_execute_command($res);
  98. }
  99. =head2 submit
  100. Description:
  101. Submit a FORM element. The submit command may also be applied to any element
  102. that is a descendant of a FORM element.
  103. Compatibility:
  104. On webdriver3 enabled servers, this uses a JS shim, which may not submit correctly depending on the element you are attempting to submit.
  105. Try clicking it if possible instead.
  106. Usage:
  107. $elem->submit();
  108. =cut
  109. sub submit {
  110. my ($self) = @_;
  111. return $self->driver->execute_script("if (typeof arguments[0].submit === 'function') { return arguments[0].submit(); }; return 0;", {'element-6066-11e4-a52e-4f735466cecf'=> $self->{id}} ) if $self->driver->{is_wd3} && !(grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge});
  112. my $res = { 'command' => 'submitElement', 'id' => $self->id };
  113. return $self->_execute_command($res);
  114. }
  115. =head2 send_keys
  116. Description:
  117. Send a sequence of key strokes to an element. If you want to send specific
  118. Keyboard events, then use the WDKeys module along with theis method. See e.g.
  119. for reference
  120. Input: 1
  121. Required:
  122. {ARRAY | STRING} - Array of strings or a string.
  123. Usage:
  124. $elem->send_keys('abcd', 'efg');
  125. $elem->send_keys('hijk');
  126. or
  127. # include the WDKeys module
  128. use Selenium::Remote::WDKeys;
  129. .
  130. .
  131. $elem->send_keys(KEYS->{'space'}, KEYS->{'enter'});
  132. =cut
  133. sub send_keys {
  134. my ( $self, @strings ) = @_;
  135. croak "no keys to send" unless scalar @strings >= 1;
  136. my $res = { 'command' => 'sendKeysToElement', 'id' => $self->id };
  137. # We need to send an array of single characters to be WebDriver
  138. # spec compatible. That is, for @strings = ('hel', 'lo'), the
  139. # corresponding value must be ('h', 'e', 'l', 'l', 'o' ). This
  140. # format conforms with the Spec AND works with the Selenium
  141. # standalone server.
  142. my $strings = join('', map { $_."" } @strings);
  143. my $params = {
  144. 'value' => [ split('', $strings) ],
  145. text => $strings,
  146. };
  147. return $self->_execute_command( $res, $params );
  148. }
  149. =head2 is_selected
  150. Description:
  151. Determine if an OPTION element, or an INPUT element of type checkbox or
  152. radiobutton is currently selected.
  153. Output:
  154. BOOLEAN - whether the element is selected
  155. Usage:
  156. $elem->is_selected();
  157. =cut
  158. sub is_selected {
  159. my ($self) = @_;
  160. return $self->get_property('checked') if $self->driver->{is_wd3} && !(grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge});
  161. my $res = { 'command' => 'isElementSelected', 'id' => $self->id };
  162. return $self->_execute_command($res);
  163. }
  164. =head2 set_selected
  165. Description:
  166. Select an OPTION element, or an INPUT element of type checkbox or radiobutton.
  167. Forces selected=1 on the element..
  168. Usage:
  169. $elem->set_selected();
  170. =cut
  171. sub set_selected {
  172. my ($self) = @_;
  173. if ($self->driver->{is_wd3}) {
  174. return if $self->is_selected();
  175. return $self->click();
  176. }
  177. my $res = { 'command' => 'setElementSelected', 'id' => $self->id };
  178. return $self->_execute_command($res);
  179. }
  180. =head2 toggle
  181. Description:
  182. Toggle whether an OPTION element, or an INPUT element of type checkbox or
  183. radiobutton is currently selected.
  184. Output:
  185. BOOLEAN - Whether the element is selected after toggling its state.
  186. Usage:
  187. $elem->toggle();
  188. =cut
  189. sub toggle {
  190. my ($self) = @_;
  191. if ($self->driver->{is_wd3}) {
  192. return $self->click() unless $self->is_selected();
  193. return $self->driver->execute_script(qq/ if (arguments[0].checked) { arguments[0].checked = 0 }; return arguments[0].checked; /, {'element-6066-11e4-a52e-4f735466cecf'=> $self->{id}});
  194. }
  195. my $res = { 'command' => 'toggleElement', 'id' => $self->id };
  196. return $self->_execute_command($res);
  197. }
  198. =head2 is_enabled
  199. Description:
  200. Determine if an element is currently enabled.
  201. Output:
  202. BOOLEAN - Whether the element is enabled.
  203. Usage:
  204. $elem->is_enabled();
  205. =cut
  206. sub is_enabled {
  207. my ($self) = @_;
  208. if ($self->driver->{is_wd3} && !(grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge})) {
  209. return 1 if $self->get_tag_name() ne 'input';
  210. return $self->get_property('disabled') ? 0 : 1;
  211. }
  212. my $res = { 'command' => 'isElementEnabled', 'id' => $self->id };
  213. return $self->_execute_command($res);
  214. }
  215. =head2 get_element_location
  216. Description:
  217. Determine an element's location on the page. The point (0, 0) refers to the
  218. upper-left corner of the page.
  219. Compatibility:
  220. On WebDriver 3 enabled servers, this is an alias for get_element_rect().
  221. Output:
  222. HASH - The X and Y coordinates for the element on the page.
  223. Usage:
  224. $elem->get_element_location();
  225. This method is DEPRECATED on webdriver3 enabled servers.
  226. =cut
  227. sub get_element_location {
  228. my ($self) = @_;
  229. if ($self->driver->{is_wd3} && !(grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge})) {
  230. my $data = $self->get_element_rect();
  231. delete $data->{height};
  232. delete $data->{width};
  233. return $data;
  234. }
  235. my $res = { 'command' => 'getElementLocation', 'id' => $self->id };
  236. return $self->_execute_command($res);
  237. }
  238. =head2 get_size
  239. Description:
  240. Determine an element's size in pixels. The size will be returned with width
  241. and height properties.
  242. Compatibility:
  243. On WebDriver 3 enabled servers, this is an alias for get_element_rect().
  244. Output:
  245. HASH - The width and height of the element, in pixels.
  246. Usage:
  247. $elem->get_size();
  248. This method is DEPRECATED on webdriver3 enabled servers.
  249. =cut
  250. sub get_size {
  251. my ($self) = @_;
  252. if ($self->driver->{is_wd3} && !(grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge})) {
  253. my $data = $self->get_element_rect();
  254. delete $data->{x};
  255. delete $data->{y};
  256. return $data;
  257. }
  258. my $res = { 'command' => 'getElementSize', 'id' => $self->id };
  259. return $self->_execute_command($res);
  260. }
  261. =head2 get_element_rect
  262. Get the element's size AND location in a hash.
  263. Example Output:
  264. { x => 0, y => 0, height => 10, width => 10 }
  265. =cut
  266. sub get_element_rect {
  267. my ($self) = @_;
  268. my $res = { 'command' => 'getElementRect', 'id' => $self->id };
  269. return $self->_execute_command($res);
  270. }
  271. =head2 get_element_location_in_view
  272. Description:
  273. Determine an element's location on the screen once it has been scrolled
  274. into view.
  275. Note: This is considered an internal command and should only be used to
  276. determine an element's location for correctly generating native events.
  277. Compatibility:
  278. On Webdriver3 servers, we have to implement this with a JS shim.
  279. This means in some contexts, you won't get any position returned, as the element isn't considered an element internally.
  280. You may have to go up the element stack to find the element that actually has the bounding box.
  281. Output:
  282. {x:number, y:number} The X and Y coordinates for the element on the page.
  283. Usage:
  284. $elem->get_element_location_in_view();
  285. =cut
  286. sub get_element_location_in_view {
  287. my ($self) = @_;
  288. #XXX chrome is dopey here
  289. return $self->driver->execute_script(qq{
  290. if (typeof(arguments[0]) !== 'undefined' && arguments[0].nodeType === Node.ELEMENT_NODE) {
  291. arguments[0].scrollIntoView();
  292. var pos = arguments[0].getBoundingClientRect();
  293. return {y:pos.top,x:pos.left};
  294. }
  295. return {};
  296. }, {'element-6066-11e4-a52e-4f735466cecf'=> $self->{id}} ) if $self->driver->{is_wd3} && grep { $self->driver->browser_name eq $_ } ('firefox','internet explorer');
  297. my $res = { 'command' => 'getElementLocationInView', 'id' => $self->id };
  298. return $self->_execute_command($res);
  299. }
  300. =head2 get_tag_name
  301. Description:
  302. Query for an element's tag name.
  303. Output:
  304. STRING - The element's tag name, as a lowercase string.
  305. Usage:
  306. $elem->get_tag_name();
  307. =cut
  308. sub get_tag_name {
  309. my ($self) = @_;
  310. my $res = { 'command' => 'getElementTagName', 'id' => $self->id };
  311. return $self->_execute_command($res);
  312. }
  313. =head2 clear
  314. Description:
  315. Clear a TEXTAREA or text INPUT element's value.
  316. Usage:
  317. $elem->clear();
  318. =cut
  319. sub clear {
  320. my ($self) = @_;
  321. my $res = { 'command' => 'clearElement', 'id' => $self->id };
  322. return $self->_execute_command($res);
  323. }
  324. =head2 get_attribute
  325. Description:
  326. Get the value of an element's attribute.
  327. Compatibility:
  328. In older webDriver, this actually got the value of an element's property.
  329. If you want to get the initial condition (e.g. the values in the tag hardcoded in HTML), pass 1 as the second argument.
  330. This can only done on WebDriver 3 enabled servers.
  331. Input: 2
  332. Required:
  333. STRING - name of the attribute of the element
  334. Optional:
  335. BOOLEAN - "I really mean that I want the initial condition, quit being so compatible!!!"
  336. Output:
  337. {STRING | NULL} The value of the attribute, or null if it is not set on the element.
  338. Usage:
  339. $elem->get_attribute('name',1);
  340. =cut
  341. sub get_attribute {
  342. my ( $self, $attr_name, $no_i_really_mean_it ) = @_;
  343. if ( not defined $attr_name ) {
  344. croak 'Attribute name not provided';
  345. }
  346. return $self->get_property($attr_name) if $self->driver->{is_wd3} && !(grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge}) && !$no_i_really_mean_it;
  347. my $res = {
  348. 'command' => 'getElementAttribute',
  349. 'id' => $self->id,
  350. 'name' => $attr_name,
  351. };
  352. return $self->_execute_command($res);
  353. }
  354. =head2 get_property
  355. Gets the C<Current Value> of an element's attribute.
  356. Takes a named property as an argument.
  357. Only available on WebDriver 3 enabled servers.
  358. =cut
  359. sub get_property {
  360. my ($self,$prop) = @_;
  361. return $self->get_attribute($prop) if $self->driver->{is_wd3} && (grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge});
  362. my $res = { 'command' => 'getElementProperty', id => $self->id, name => $prop };
  363. return $self->_execute_command($res);
  364. }
  365. =head2 get_value
  366. Description:
  367. Query for the value of an element, as determined by its value attribute.
  368. Output:
  369. {STRING | NULL} The element's value, or null if it doesn't have a value attribute.
  370. Usage:
  371. $elem->get_value();
  372. =cut
  373. sub get_value {
  374. my ($self) = @_;
  375. return $self->get_attribute('value');
  376. }
  377. =head2 get_style
  378. =head2 is_displayed
  379. Description:
  380. Determine if an element is currently displayed.
  381. Note: This does *not* tell you an element's 'visibility' property; as it still takes up space in the DOM and is therefore considered 'displayed'.
  382. Output:
  383. BOOLEAN - Whether the element is displayed.
  384. Usage:
  385. $elem->is_displayed();
  386. =cut
  387. sub is_displayed {
  388. my ($self) = @_;
  389. if ($self->driver->{is_wd3} && !(grep { $self->driver->browser_name eq $_ } qw{chrome MicrosoftEdge})) {
  390. return 0 if $self->get_tag_name() eq 'input' && $self->get_property('type') eq 'hidden'; #hidden type inputs
  391. return int($self->get_css_attribute('display') ne 'none');
  392. }
  393. my $res = { 'command' => 'isElementDisplayed', 'id' => $self->id };
  394. return $self->_execute_command($res);
  395. }
  396. =head2 is_hidden
  397. Description:
  398. Determine if an element is currently hidden.
  399. Output:
  400. BOOLEAN - Whether the element is hidden.
  401. Usage:
  402. $elem->is_hidden();
  403. =cut
  404. sub is_hidden {
  405. my ($self) = @_;
  406. return ! $self->is_displayed();
  407. }
  408. =head2 drag
  409. Alias for Selenium::ActionChains::drag_and_drop().
  410. Provide element you wish to drag to as argument.
  411. my $target = $driver->find_element('receptacle','id');
  412. my $subject = $driver->find_element('thingy','id');
  413. $subject->drag($target);
  414. =cut
  415. sub drag {
  416. my ($self,$target) = @_;
  417. require Selenium::ActionChains;
  418. my $chain = Selenium::ActionChians->new( driver => $self->driver );
  419. return $chain->drag_and_drop($self,$target)->perform();
  420. }
  421. =head2 get_text
  422. Description:
  423. Get the innerText of the element.
  424. Output:
  425. STRING - innerText of an element
  426. Usage:
  427. $elem->get_text();
  428. =cut
  429. sub get_text {
  430. my ($self) = @_;
  431. my $res = { 'command' => 'getElementText', 'id' => $self->id };
  432. return $self->_execute_command($res);
  433. }
  434. =head2 get_css_attribute
  435. Description:
  436. Query the value of an element's computed CSS property. The CSS property to
  437. query should be specified using the CSS property name, not the JavaScript
  438. property name (e.g. background-color instead of backgroundColor).
  439. Input: 1
  440. Required:
  441. STRING - name of the css-attribute
  442. Output:
  443. STRING - Value of the css attribute
  444. Usage:
  445. $elem->get_css_attribute('background-color');
  446. =cut
  447. sub get_css_attribute {
  448. my ( $self, $attr_name ) = @_;
  449. if ( not defined $attr_name ) {
  450. croak 'CSS attribute name not provided';
  451. }
  452. my $res = {
  453. 'command' => 'getElementValueOfCssProperty',
  454. 'id' => $self->id,
  455. 'property_name' => $attr_name,
  456. };
  457. return $self->_execute_command($res);
  458. }
  459. =head2 describe
  460. Description:
  461. Describe the identified element
  462. Usage:
  463. $elem->describe();
  464. Note: DEPRECATED as of 2.42.2 -- use get_text, get_value, is_displayed, or
  465. whatever appropriate WebElement function you need instead
  466. Entirely unsupported on WebDriver 3 enabled servers.
  467. =cut
  468. sub describe {
  469. my ($self) = @_;
  470. my $res = { 'command' => 'describeElement', 'id' => $self->id };
  471. return $self->_execute_command($res);
  472. }
  473. =head2 screenshot
  474. Description:
  475. Get a screenshot of the visible region that is a subset of the element's bounding box as a base64 encoded image.
  476. Compatibility:
  477. Only available on Webdriver3 enabled selenium servers.
  478. Input (optional):
  479. $scroll_into_view - BOOLEAN default true. If false, will not scroll the element into the viewport first.
  480. Failing to do so may result in an image being cropped partially or entirely.
  481. Output:
  482. STRING - base64 encoded image
  483. Usage:
  484. print $element->screenshot();
  485. To conveniently write the screenshot to a file, see L</capture_screenshot>.
  486. =cut
  487. sub screenshot {
  488. my ($self, $scroll) = @_;
  489. $scroll //= 1;
  490. my $res = { 'command' => 'elementScreenshot', id => $self->id };
  491. my $input = {scroll => int($scroll) };
  492. return $self->_execute_command($res, $input);
  493. }
  494. =head2 capture_screenshot
  495. Description:
  496. Capture a screenshot of said element and save as a PNG to provided file name.
  497. Compatibility:
  498. Only available on Webdriver3 enabled selenium servers.
  499. Input (optional):
  500. $scroll_into_view - BOOLEAN default true. If false, will not scroll the element into the viewport first.
  501. Failing to do so may result in an image being cropped partially or entirely.
  502. Output:
  503. TRUE - (Screenshot is written to file)
  504. Usage:
  505. $element->capture_screenshot($filename);
  506. =cut
  507. sub capture_screenshot {
  508. my ( $self, $filename, $scroll ) = @_;
  509. croak '$filename is required' unless $filename;
  510. open( my $fh, '>', $filename );
  511. binmode $fh;
  512. print $fh MIME::Base64::decode_base64( $self->screenshot($scroll) );
  513. CORE::close $fh;
  514. return 1;
  515. }
  516. 1;