美丽的团队。找到所有人()方法无法处理命名空间标记

2024-06-08 04:31:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我今天在和BeautifulSoup一起工作时遇到了一个非常奇怪的行为。在

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

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

我试图用BeautifulSoup获取<ix:nonfraction>标记的内容。在

使用find方法时一切正常:

^{pr2}$

但是,当尝试使用find_all方法时,我希望返回一个包含这个元素的列表,事实并非如此!在

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

实际上,find_all似乎每次在我要搜索的标记中出现冒号时都会返回一个空列表。在

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

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


Tags: 方法标记元素内容列表htmlbodyall
3条回答

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

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

下面是beautifulsoup源代码的一个片段,显示了调用find或{}时发生的情况。您将看到find只是用limit=1调用find_all。在_find_all中,它检查条件:

^{pr2}$

如果它达到了这个条件,那么它最终可能会变成这样:

# 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不满足任何前面的条件,那么就可以找到元素。在

美化组4==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
>>> soup.findAll('ix:nonfraction')
[<ix:nonfraction>lele</ix:nonfraction>]

FindAll Documentation

保留标记名为空并使用ix作为属性。在

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

效果很好

EDIT:“ix:nonfraction”不是标记名,因此汤。找到所有(“ix:nonfraction”)为不存在的标记返回了一个空列表。在

相关问题 更多 >

    热门问题