diff options
author | Leonard Richardson <leonardr@segfault.org> | 2015-06-25 21:41:23 -0400 |
---|---|---|
committer | Leonard Richardson <leonardr@segfault.org> | 2015-06-25 21:41:23 -0400 |
commit | c7b7a22a46064c6362eebb5670022b06bf601daf (patch) | |
tree | 6f8a994f6461b5e57b55278282fd72a1128473ac /bs4/element.py | |
parent | 51044d613cc782d883a6eb3cd0d3dc391e13c23b (diff) |
Introduced the select_one() method, which uses a CSS selector but
only returns the first match, instead of a list of
matches. [bug=1349367]
Diffstat (limited to 'bs4/element.py')
-rw-r--r-- | bs4/element.py | 12 |
1 files changed, 11 insertions, 1 deletions
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)) |