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))
Hi all,Xóa nút con đầu tiên sử dụng BeautifulSoup
Tôi cố gắng để làm một số phân tích các tập tin sử dụng BeautifulSoup để làm sạch chúng tăng nhẹ. Các chức năng tôi muốn là tôi muốn xóa bảng đầu tiên đó là bất cứ nơi nào trong một bảng, ví dụ:
<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>
Tại thời điểm này, mã của tôi được thiết lập để tìm tất cả các bảng trong một bảng và tôi đã một tạo thành một phương pháp .REMOVE()
để hiển thị những gì tôi muốn thực hiện. Làm thế nào tôi có thể thực sự loại bỏ yếu tố này?
Tl; dr -
Làm thế nào tôi có thể thích ứng với mã của tôi để tìm chỉ bảng lồng nhau đầu tiên trong tệp .
Tôi làm cách nào để xóa bảng này?
Rất cám ơn cho câu trả lời. Có thể xóa tất cả các nút con của bảng không? :) Cảm ơn. –
@ SimonKiely bạn có nghĩa là các thẻ 'table' bên trong khác bên ngoài không? Cảm ơn. – alecxe