迭代并使用目录中的HTML文件 - python

时间:2016-12-06 14:02:42

标签: html python-3.x screen-scraping

我需要遍历给定目录中的.html文件并从中删除数据。到目前为止这是我的代码,我将如何访问里面的脚本?

import os
directory ='/Users/xxxxx/Documents/sample/'
for filename in os.listdir(directory):
    if filename.endswith('.html'):
        print(os.path.join(directory,filename))
    else:
        continue

(系统:Mac / Python3.x)

1 个答案:

答案 0 :(得分:2)

你可以这样做:

import os
from bs4 import BeautifulSoup

directory ='/Users/xxxxx/Documents/sample/'
for filename in os.listdir(directory):
    if filename.endswith('.html'):
        fname = os.path.join(directory,filename)
        with open(fname, 'r') as f:
            soup = BeautifulSoup(f.read(),'html.parser')
            # parse the html as you wish