BeautifulSoup寻找特定的孩子

jay*_*jay 1 python children beautifulsoup elements

我想使用BeautifulSoup在子元素中搜索特定属性,从我可以看到使用下面的方法,每个子节点都是一个字符串(child ['value']给我"字符串索引必须是整数"),这是不允许的选择基于属性或返回这些属性,这是我需要做的事情.

def get_value(container):
    html_file = open(html_path)
    html = html_file.read()
    soup = BeautifulSoup(html)
    values = {}
    container = soup.find(attrs={"name" : container})
    if (container.contents != []):
        for child in container.children:
            value = unicode(child['value']) # i would like to be able to search throught these children based on their attributes, and return one or more of their values
return value
Run Code Online (Sandbox Code Playgroud)

可能可以通过进一步child_soup Beautifulsoup(child)然后找到命令解决这个问题,但这看起来真的太可怕了,有人得到了更好的解决方案吗?

Kos*_*Kos 9

container.children是一个提供Tag对象的生成器,因此您可以正常操作它们.

您也可能想尝试element.find_all(..., recursive=False)以寻找具有某些特征的元素的直接孩子.