2014-02-09 191 views
0

我想从源代码中删除样式标签及其内容,但它不工作,没有错误只是不分解。这是我有:BeautifulSoup去除标签

source = BeautifulSoup(open("page.html")) 
getbody = source.find('body') 
for child in getbody[0].children: 
    try: 
     if child.get('style') is not None and child.get('style') == "display:none": 
      # it in here 
      child.decompose() 
    except: 
     continue 
print source 
# display:hidden div's are still there. 
+0

您的语法无效;没有'except'处理程序。如果你使用'except:pass' * remove *'try' /'except'来查看你所掩盖的任何错误。 –

+0

'getbody [0]'也引发'KeyError'。 –

+0

我不知道该代码如何不抛出任何'SyntaxError'。 – cdonts

回答

0

下面的代码做你想做的和工作正常;做使用毯除了处理来掩盖错误:

source = BeautifulSoup(open("page.html")) 
for hidden in source.body.find_all(style='display:none'): 
    hidden.decompose() 

或者更好的是,使用正则表达式来撒网更宽一点:

import re 

source = BeautifulSoup(open("page.html")) 
for hidden in source.body.find_all(style=re.compile(r'display:\s*none')): 
    hidden.decompose() 

Tag.children只列出的直接儿童body标签,不是所有嵌套的孩子。

+0

使用'findAll(style ='display:none'):'把它排序,奇数。谢谢。当我可用时将接受答案 – user273324

+0

@ user273324:这是因为'.children'只列出直接后代,而不是子树中的所有元素。 –