使用BeautifulSoup删除第一个子节点

时间:2014-12-05 15:29:19

标签: python html parsing beautifulsoup html-parsing

import os
from bs4 import BeautifulSoup
do = dir_with_original_files = 'C:\FOLDER'
dm = dir_with_modified_files = 'C:\FOLDER'
for root, dirs, files in os.walk(do):
    for f in files:
        print f.title()
        if f.endswith('~'): #you don't want to process backups
            continue
        original_file = os.path.join(root, f)
        mf = f.split('.')
        mf = ''.join(mf[:-1])+'_mod.'+mf[-1] # you can keep the same name 
                                             # if you omit the last two lines.
                                             # They are in separate directories
                                             # anyway. In that case, mf = f
        modified_file = os.path.join(dm, mf)
        with open(original_file, 'r') as orig_f, \
             open(modified_file, 'w') as modi_f:
            soup = BeautifulSoup(orig_f.read())

            for t in soup.find_all('table'):
                for child in t.find_all("table"):#*****this is fine for now, but how would I restrict it to find only the first element?
                    child.REMOVE() #******PROBLEM HERE********

            # This is where you create your new modified file.
            modi_f.write(soup.prettify().encode(soup.original_encoding)) 

大家好,

我正在尝试使用BeautifulSoup对文件进行一些解析来稍微清理它们。我想要的功能是我想要删除表中任何位置的第一个表,例如:

<table>
  <tr>
    <td></td
  </tr>
  <tr>
    <td><table></table><-----This will be deleted</td
  </tr>
  <tr>
    <td><table></table> --- this will remain here.</td
  </tr>
</table>

目前,我的代码设置为查找表格中的所有表格,并且我有一个.REMOVE()方法来显示我想要完成的内容。我怎样才能真正删除这个元素?

Tl; dr -

  • 如何调整我的代码以仅查找a中的第一个嵌套表 文件

  • 如何删除此表?

1 个答案:

答案 0 :(得分:6)

找到表格中的第一个表格并在其上调用extract()

inner_table = soup.find('table').find('table')  # or just soup.table.table
inner_table.extract()