From c7b7a22a46064c6362eebb5670022b06bf601daf Mon Sep 17 00:00:00 2001 From: Leonard Richardson Date: Thu, 25 Jun 2015 21:41:23 -0400 Subject: Introduced the select_one() method, which uses a CSS selector but only returns the first match, instead of a list of matches. [bug=1349367] --- bs4/element.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'bs4/element.py') diff --git a/bs4/element.py b/bs4/element.py index 454d34b..cc21c5c 100644 --- a/bs4/element.py +++ b/bs4/element.py @@ -1258,7 +1258,14 @@ class Tag(PageElement): _selector_combinators = ['>', '+', '~'] _select_debug = False - def select(self, selector, _candidate_generator=None): + def select_one(self, selector): + """Perform a CSS selection operation on the current element.""" + value = self.select(selector, limit=1) + if value: + return value[0] + return None + + def select(self, selector, _candidate_generator=None, limit=None): """Perform a CSS selection operation on the current element.""" # Remove whitespace directly after the grouping operator ',' @@ -1433,6 +1440,7 @@ class Tag(PageElement): else: _use_candidate_generator = _candidate_generator + count = 0 for tag in current_context: if self._select_debug: print " Running candidate generator on %s %s" % ( @@ -1457,6 +1465,8 @@ class Tag(PageElement): # don't include it in the context more than once. new_context.append(candidate) new_context_ids.add(id(candidate)) + if limit and len(new_context) >= limit: + break elif self._select_debug: print " FAILURE %s %s" % (candidate.name, repr(candidate.attrs)) -- cgit v1.2.3