BeautifulSoup.find_all() 方法不适用于命名空间标签

BeautifulSoup.find_all() method not working with namespaced tags

我今天在使用 BeautifulSoup 时遇到了一个非常奇怪的行为。

让我们看一个非常简单的 html 片段:

<html><body><ix:nonfraction>lele</ix:nonfraction></body></html>

我正在尝试使用 BeautifulSoup 获取 <ix:nonfraction> 标签的内容。

使用 find 方法时一切正常:

from bs4 import BeautifulSoup

html = "<html><body><ix:nonfraction>lele</ix:nonfraction></body></html>"

soup = BeautifulSoup(html, 'lxml') # The parser used here does not matter

soup.find('ix:nonfraction')

>>> <ix:nonfraction>lele</ix:nonfraction>

但是,当尝试使用 find_all 方法时,我希望得到一个包含此单个元素的列表 returned,但事实并非如此!

soup.find_all('ix:nonfraction')
>>> []

事实上,每当我正在搜索的标签中出现冒号时,find_all 似乎 return 一个空列表。

我已经能够在两台不同的计算机上重现该问题。

有没有人有解释,更重要的是,有解决方法吗? 我需要使用 find_all 方法只是因为我的实际情况需要我在整个 html 页面上获取所有这些标签。

将标签名称留空并使用 ix 作为属性。

soup.find_all({"ix:nonfraction"}) 

效果不错

编辑:'ix:nonfraction' 不是标签名称,因此 soup.find_all("ix:nonfraction") 为不存在的标签返回了一个空列表。

@yosemite_k 的解决方案之所以有效,是因为在 bs4 的源代码中,它跳过了导致此行为的特定条件。事实上,您可以做很多变化来产生相同的结果。示例:

soup.find_all({"ix:nonfraction"})
soup.find_all('ix:nonfraction', limit=1)
soup.find_all('ix:nonfraction', text=True)

下面是 beautifulsoup 源代码的一个片段,显示了调用 findfind_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