Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add attributes method to get attributes for element #237

Merged
merged 1 commit into from
Jun 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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