【问题标题】:iterate through and use HTML files in a directory - python遍历并使用目录中的 HTML 文件 - python
【发布时间】:2016-12-06 14:02:41
【问题描述】:

我需要遍历给定目录中的 .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)

【问题讨论】:

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


    【解决方案1】:

    你可以这样做:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多