17

如果我只有一个 IP 地址,如何列出文件和文件夹?

使用 urllib 等,我只能显示index.html文件的内容。但是,如果我还想查看根目录中的文件怎么办?

我正在寻找一个示例来说明如何在需要时实现用户名和密码。(大多数时候 index.html 是公开的,但有时其他文件不是)。

4

5 回答 5

37

用于requests获取页面内容并BeautifulSoup解析结果。
例如,如果我们iso在以下位置搜索所有文件http://cdimage.debian.org/debian-cd/8.2.0-live/i386/iso-hybrid/

from bs4 import BeautifulSoup
import requests

url = 'http://cdimage.debian.org/debian-cd/8.2.0-live/i386/iso-hybrid/'
ext = 'iso'

def listFD(url, ext=''):
    page = requests.get(url).text
    print page
    soup = BeautifulSoup(page, 'html.parser')
    return [url + '/' + node.get('href') for node in soup.find_all('a') if node.get('href').endswith(ext)]

for file in listFD(url, ext):
    print file
于 2016-01-11T10:12:07.537 回答
13

正如另一个答案所说,您不能直接通过 HTTP 获取目录列表。是 HTTP 服务器“决定”给你什么。有些会给你一个 HTML 页面,显示“目录”内所有文件的链接,有些会给你一些页面(index.html),有些甚至不会将“目录”解释为一个。

例如,您可能有一个指向“http://localhost/user-login/”的链接:这并不意味着在服务器的文档根目录中有一个名为 user-login 的目录。服务器将其解释为指向某个页面的“链接”。

现在,要实现您想要的,您要么必须使用 HTTP 以外的其他东西(您要访问的“IP 地址”上的 FTP 服务器就可以完成这项工作),或者在该机器上设置一个 HTTP 服务器,为每个路径(http://192.168.2.100/directory)其中的文件列表(无论格式)并通过Python解析。

如果服务器提供“/bla/bla 索引”类型的页面(如 Apache 服务器所做的目录列表),您可以解析 HTML 输出以找出文件和目录的名称。如果没有(例如自定义 index.html,或服务器决定给您的任何内容),那么您就不走运了 :(,您不能这样做。

于 2012-06-13T22:16:26.707 回答
4

HTTP 不适用于“文件”和“目录”。选择不同的协议。

于 2012-06-13T21:29:36.100 回答
4

Zety 提供了一个不错的紧凑型解决方案。我将通过使requests组件更健壮和功能更强大来添加他的示例:

import requests
from bs4 import BeautifulSoup

def get_url_paths(url, ext='', params={}):
    response = requests.get(url, params=params)
    if response.ok:
        response_text = response.text
    else:
        return response.raise_for_status()
    soup = BeautifulSoup(response_text, 'html.parser')
    parent = [url + node.get('href') for node in soup.find_all('a') if node.get('href').endswith(ext)]
    return parent

url = 'http://cdimage.debian.org/debian-cd/8.2.0-live/i386/iso-hybrid'
ext = 'iso'
result = get_url_paths(url, ext)
print(result)
于 2018-03-30T02:04:17.290 回答
3

您可以使用以下脚本获取 HTTP 服务器中子目录和目录中所有文件的名称。文件编写器可用于下载它们。

from urllib.request import Request, urlopen, urlretrieve
from bs4 import BeautifulSoup
def read_url(url):
    url = url.replace(" ","%20")
    req = Request(url)
    a = urlopen(req).read()
    soup = BeautifulSoup(a, 'html.parser')
    x = (soup.find_all('a'))
    for i in x:
        file_name = i.extract().get_text()
        url_new = url + file_name
        url_new = url_new.replace(" ","%20")
        if(file_name[-1]=='/' and file_name[0]!='.'):
            read_url(url_new)
        print(url_new)

read_url("www.example.com")
于 2016-11-17T17:34:06.443 回答