Skip to content

Commit

Permalink
Add attributes method to browser
Browse files Browse the repository at this point in the history
  • Loading branch information
digitronik committed Jun 27, 2023
1 parent ff2c223 commit 2577847
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/widgetastic/browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@
})(arguments);
"""

EXTRACT_ATTRIBUTES_OF_ELEMENT = """
var items = {};
for (index = 0; index < arguments[0].attributes.length; ++index) {
items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value
};
return items;
"""


if TYPE_CHECKING:
from .widget.base import Widget

Expand Down Expand Up @@ -795,6 +804,23 @@ def text(self, locator: LocatorAlias, *args, **kwargs) -> str:
self.logger.debug("text(%r) => %r", locator, crop_string_middle(result))
return result

@retry_stale_element
def attributes(self, locator: LocatorAlias, *args, **kwargs) -> Dict:
"""Return a dict of attributes attached to the element.
Args: See :py:meth:`elements`
Returns:
A :py:class:`dict` of attributes and respective values.
"""
result = self.execute_script(
EXTRACT_ATTRIBUTES_OF_ELEMENT,
self.element(locator, *args, **kwargs),
silent=True,
)
self.logger.debug("css attributes for %r => %r", locator, result)
return result

@retry_stale_element
def get_attribute(self, attr: str, *args, **kwargs) -> Optional[str]:
return self.element(*args, **kwargs).get_attribute(attr)
Expand Down
4 changes: 4 additions & 0 deletions testing/test_browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,10 @@ def test_text_invisible(browser):
assert browser.text("#invisible") == "This is invisible"


def test_attributes(browser):
assert browser.attributes("//h1") == {"class": "foo bar", "id": "hello"}


def test_get_attribute(browser):
assert browser.get_attribute("id", "//h1") == "hello"

Expand Down

0 comments on commit 2577847

Please sign in to comment.