diff --git a/requests_html.py b/requests_html.py index ee2f6b2..5081a01 100644 --- a/requests_html.py +++ b/requests_html.py @@ -123,12 +123,27 @@ class BaseParser: return elements def xpath(self, selector: str, first: bool = False, _encoding: str = None): - """Given an XPath selector, returns a list of :class:`Element ` objects. + """Given an XPath selector, returns a list of + :class:`Element ` objects. - See W3School's `XPath Examples `_ for more details. + If a sub-selector is specified (e.g. ``//a/@href``), a simple + list of results is returned. + + See W3School's `XPath Examples + `_ + for more details. + + If ``first`` is ``True``, only returns the first + :class:`Element ` found. + """ + selected = self.lxml.xpath(selector) + try: + c = [Element(element=e, url=self.url, default_encoding=_encoding or self.encoding) for e in selected] + # Sanity check. + [e.keys for e in c] + except AttributeError: + c = selected - If ``first`` is ``True``, only returns the first :class:`Element ` found.""" - c = [Element(element=e, url=self.url, default_encoding=_encoding or self.encoding) for e in self.lxml.xpath(selector)] if first: try: return c[0]