BeautifulSoup.find_all() method not working with namespaced tags

我是研究僧i 提交于 2021-02-18 10:59:12

问题


I have encountered a very strange behaviour while working with BeautifulSoup today.

Let's have a look at a very simple html snippet:

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

I am trying to get the content of the <ix:nonfraction> tag with BeautifulSoup.

Everything works fine when using the find method:

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>

However, when trying to use the find_all method, I expect to have a list with this single element returned, which is not the case !

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

In fact, find_all seems to return an empty list everytime a colon is present in the tag I am searching for.

I have been able to reproduce the problem on two different computers.

Does anyone have an explanation, and more importantly, a workaround ? I need to use the find_all method simply because my actual case requires me to get all these tags on a whole html page.


回答1:


The reason @yosemite_k's solution works is because in the source code of bs4, it's skipping a certain condition which causes this behavior. You can in fact do many variations which will produce this same result. Examples:

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

Below is a snippet from the source code of beautifulsoup that shows what happens when you call find or find_all. You will see that find just calls find_all with limit=1. In _find_all it checks for a condition:

if text is None and not limit and not attrs and not kwargs:

If it hits that condition, then the it might eventually make it down to this condition:

# Optimization to find all tags with a given name.
if name.count(':') == 1:

If it makes it there, then it does a reassignment of name:

# This is a name with a prefix.
prefix, name = name.split(':', 1)

This is where you're behavior is different. As long as find_all doesn't meet any of the prior conditions, then you'll find the element.

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



回答2:


leaving the tag name empty and using ix as attribute.

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

works well

EDIT: 'ix:nonfraction' is not a tag name, so soup.find_all("ix:nonfraction") returned an empty list for a non existent tag.




回答3:


>>> soup.findAll('ix:nonfraction')
[<ix:nonfraction>lele</ix:nonfraction>]

FindAll Documentation



来源:https://stackoverflow.com/questions/44680303/beautifulsoup-find-all-method-not-working-with-namespaced-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!