Skip to main content
 首页 » 编程设计

python之BeautifulSoup 寻找特定的 child

2025年05月04日10freeliver54

我想使用 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 

可能可以通过进一步的 child_soup Beautifulsoup(child) 然后使用 find 命令来解决这个问题,但这看起来真的很糟糕,有人有更好的解决方案吗?

请您参考如下方法:

container.children 是一个生成器,提供了Tag对象,所以你可以正常操作它们。

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