@yosemite_k 的解决方案之所以有效,是因为在 bs4 的源代码中,它跳过了导致此行为的某个条件。事实上,您可以做许多变化,从而产生相同的结果。例子:
soup.find_all({"ix:nonfraction"})
soup.find_all('ix:nonfraction', limit=1)
soup.find_all('ix:nonfraction', text=True)
下面是来自beautifulsoup 源代码的sn-p,它显示了当您调用find 或find_all 时会发生什么。你会看到find 只是用limit=1 调用find_all。在_find_all 中,它检查一个条件:
if text is None and not limit and not attrs and not kwargs:
如果它达到那个条件,那么它最终可能会降到这个条件:
# Optimization to find all tags with a given name.
if name.count(':') == 1:
如果它成功了,那么它会重新分配name:
# This is a name with a prefix.
prefix, name = name.split(':', 1)
这就是你的行为不同的地方。只要find_all 不满足任何先验条件,那么您就会找到该元素。
beautifulsoup4==4.6.0
def find(self, name=None, attrs={}, recursive=True, text=None,
**kwargs):
"""Return only the first child of this Tag matching the given
criteria."""
r = None
l = self.find_all(name, attrs, recursive, text, 1, **kwargs)
if l:
r = l[0]
return r
findChild = find
def find_all(self, name=None, attrs={}, recursive=True, text=None,
limit=None, **kwargs):
"""Extracts a list of Tag objects that match the given
criteria. You can specify the name of the Tag and any
attributes you want the Tag to have.
The value of a key-value pair in the 'attrs' map can be a
string, a list of strings, a regular expression object, or a
callable that takes a string and returns whether or not the
string matches for some custom definition of 'matches'. The
same is true of the tag name."""
generator = self.descendants
if not recursive:
generator = self.children
return self._find_all(name, attrs, text, limit, generator, **kwargs)
def _find_all(self, name, attrs, text, limit, generator, **kwargs):
"Iterates over a generator looking for things that match."
if text is None and 'string' in kwargs:
text = kwargs['string']
del kwargs['string']
if isinstance(name, SoupStrainer):
strainer = name
else:
strainer = SoupStrainer(name, attrs, text, **kwargs)
if text is None and not limit and not attrs and not kwargs:
if name is True or name is None:
# Optimization to find all tags.
result = (element for element in generator
if isinstance(element, Tag))
return ResultSet(strainer, result)
elif isinstance(name, str):
# Optimization to find all tags with a given name.
if name.count(':') == 1:
# This is a name with a prefix.
prefix, name = name.split(':', 1)
else:
prefix = None
result = (element for element in generator
if isinstance(element, Tag)
and element.name == name
and (prefix is None or element.prefix == prefix)
)
return ResultSet(strainer, result)
results = ResultSet(strainer)
while True:
try:
i = next(generator)
except StopIteration:
break
if i:
found = strainer.search(i)
if found:
results.append(found)
if limit and len(results) >= limit:
break
return results