xpath improvements

Signed-off-by: Kenneth Reitz <me@kennethreitz.org>
This commit is contained in:
2018-02-28 06:49:21 -05:00
parent 65f627148c
commit 495b0c3bfd
+19 -4
View File
@@ -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 <Element>` objects.
"""Given an XPath selector, returns a list of
:class:`Element <Element>` objects.
See W3School's `XPath Examples <https://www.w3schools.com/xml/xpath_examples.asp>`_ 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
<https://www.w3schools.com/xml/xpath_examples.asp>`_
for more details.
If ``first`` is ``True``, only returns the first
:class:`Element <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 <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]