【发布时间】:2014-12-24 08:52:54
【问题描述】:
我正在尝试通过使用此处建议的模型enter link description here 来使用 BeautifulSoup 提取固定标签之间的信息@
我的文件夹中有很多 .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)
【问题讨论】:
标签: python python-2.7 beautifulsoup text-files extract