2013-10-21 50 views
1

我想通过使用BeautifulSoup特定属性的子元素进行搜索,从我可以使用下面的方法每个孩子是一个字符串(子见[“值”]给了我“字符串索引必须是整数“),它不允许根据属性进行选择或返回这些属性,这显然是我需要做的。BeautifulSoup搜索特定的儿童

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命令但这似乎很可怕,任何人有一个更好的解决方案?

回答

9

container.children为发电机提供Tag对象,这样你就可以对他们的正常工作。

你可能也想尝试element.find_all(..., recursive=False)为了寻找一个元素的直接孩子一些特质。

+0

child ['value']给我“字符串索引必须是整数”,所以我认为这是一个字符串,任何想法? – jayjay

+0

哦,好点。孩子们是'Tag's和['NavigableString'](http://www.crummy.com/software/BeautifulSoup/bs4/doc/#navigablestring)。 – Kos

+0

但实际上,element.find_all()工作得很好,谢谢! – jayjay