2014-12-24 1 views
0
나는 모델을 사용하여 BeautifulSoup로 고정 태그 사이에 정보를 추출하기 위해 노력하고있어

BeautifulSoup로는

enter link description here가 내 폴더에 .html 파일을 많이 가지고 내가 얻은 결과를 저장하려면 여기 제안 BeautifulSoup 스크립트를 개별 폴더 형태로 .txt 개의 파일에 저장합니다. 이 .txt 파일은 원본 파일과 이름이 같아야하지만 추출 된 내용 만 포함해야합니다. 필자가 쓴 스크립트는 파일을 성공적으로 처리하지만 추출 된 비트는 개별 파일에 쓰지 않습니다.

import os 
import glob 
from bs4 import BeautifulSoup 

dir_path = "C:My_folder\\tmp\\" 

for file_name in glob.glob(os.path.join(dir_path, "*.html")): 
    my_data = (file_name) 
    soup = BeautifulSoup(open(my_data, "r").read()) 
    for i in soup.select('font[color="#FF0000"]'): 
     print(i.text) 
     file_path = os.path.join(dir_path, file_name) 
     text = open(file_path, mode='r').read() 
     results = i.text 
     results_dir = "C:\\My_folder\\tmp\\working" 
     results_file = file_name[:-4] + 'txt' 
     file_path = os.path.join(results_dir, results_file) 
     open(file_path, mode='w', encoding='UTF-8').write(results) 

답변

1

글로브는 전체 경로를 반환합니다. 찾은 각 font 요소에 대한 파일을 다시 열고 파일 내용을 바꿉니다. 파일의 열기를 이동 외부 루프; 당신은 정말 그들도 제대로 다시 닫혀 있도록합니다 (with 문) 컨텍스트 관리자 등의 파일을 사용해야합니다

import glob 
import os.path 
from bs4 import BeautifulSoup 

dir_path = r"C:\My_folder\tmp" 
results_dir = r"C:\My_folder\tmp\working" 

for file_name in glob.glob(os.path.join(dir_path, "*.html")): 
    with open(file_name) as html_file: 
     soup = BeautifulSoup(html_file) 

    results_file = os.path.splitext(file_name)[0] + '.txt' 
    with open(results_file, 'w') as outfile:   
     for i in soup.select('font[color="#FF0000"]'): 
      print(i.text) 
      outfile.write(i.text + '\n') 
+0

당신이 무슨 뜻인지 참조하십시오. 나는 그 일을하는 법을 몰랐다. 그냥,'AttributeError : 'module'이라는 메시지가 나타나면 스크립트에 오류가 있습니다. 'file'속성이 없습니다. 도움에 감사드립니다! – user3635159

+0

@ user3635159 : 내 사과, 그건 내 잘못이야. 이제 해결되었습니다. –

+0

건배, 지금은 효과가 있습니다. 나는 새로운 것을 배웠다. 감사. – user3635159

1
import glob 
import os 
from BeautifulSoup import BeautifulSoup 

input_dir = "/home/infogrid/Desktop/Work/stack_over/input/" 
#- Already Present on system. 
output_dir = "/home/infogrid/Desktop/Work/stack_over/output/" 

for file_name in glob.glob(input_dir+ "*.html"): 
    with open(file_name) as fp: 
     soup = BeautifulSoup(fp) 
     results_file = "%s%s.txt"%(output_dir, os.path.splitext(os.path.basename(file_name))[0]) 
     tmp = [i.text for i in soup.findAll('font') if i.get("color")=="#FF0000"] 
     with open(results_file, 'w') as fp:   
      print "\n".join(tmp) 
      fp.write("\n".join(tmp)) 
+0

잘 작동합니다. 나는 같은 일을 수행하는 한 가지 이상의 방법이 있다는 것을 좋아한다. 귀하의 제안에 감사드립니다. 그것은 두 가지 해결책을 모두 받아 들일 수있는'Stackflow'에 대한 선택의 여지가 없습니다. – user3635159