遍历索引目录的服务器URL并读取文件

问题描述

http服务器上有一个目录,其URL为http:// somehost / maindir / recent /。这个“最近”目录包含50个zip子目录。

我可以使用读取一个zip文件

 zfile = "http://somehost/maindir/recent/1.zip"
 with RemoteZip(zfile) as zip:
        for zip_info in zip.infolist():
            data = zip.read(zip_info.filename)

但是我不知道要遍历“ http:// somehost / maindir / recent /”并从每个zip读取数据。我尝试了glob,os.join,os.walk但在静脉内。 我想要这样的东西:

for zfile in baseurl: //unable to do this line.
    with RemoteZip(zfile) as zip:
        for zip_info in zip.infolist():
                data = zip.read(zip_info.filename)
            

解决方法

您无法直接获取目录列表,因为它是HTTP服务器负责返回响应,在某些情况下,您将获得一个HTML页面,显示指向“目录”中所有文件的链接,如您的案例“ http:// somehost / maindir / recent /”将为您提供最近目录中所有zip文件的列表,但格式为html。

一种解决方案可能是使用Beautifulsoup解析该html页面并从该“最近”目录页面获取zip文件的所有链接。

from bs4 import BeautifulSoup
import requests

url = 'http://somehost/maindir/recent/'


def get_files(url):
   page = requests.get(url).text
  
   soup = BeautifulSoup(page,'html.parser')
   return [url + '/' + node.get('href') for node in soup.find_all('a') if 
           node.get('href').endswith('.zip')]
file_links = get_files(url)
for zfile in file_links:
    with RemoteZip(zfile) as zip:
        for zip_info in zip.infolist():
            data = zip.read(zip_info.filename)