Python列出HTTP文件和目录。

21

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

使用urllib和其他工具,我只能显示index.html文件的内容。但是,如果我想查看根目录中有哪些文件,该怎么办呢?

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


这篇帖子 "https://dev59.com/r1PTa4cB1Zd3GeqPgBaN" 应该会对你有所帮助... 希望如此 :) - user870774
5个回答

42
使用requests获取网页内容,使用BeautifulSoup解析结果。
例如,如果我们搜索所有在http://cdimage.debian.org/debian-cd/8.2.0-live/i386/iso-hybrid/上的iso文件:
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

14

正如另一份回答所说,你不能直接通过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,或者服务器决定给你什么),那么你就没有办法了 :( ,你无法做到这一点。


非常好的答案。感谢您的帮助。确实,index.html 给了我其他文件和文件夹的名称。也许我可以尝试获取这些。 - xfscrypt
1
太好了 :) 如果是这样的话,可以尝试使用BeautifulSoup等Python中的HTML解析库进行搜索。还有其他的库也可以用于此。 - jadkik94

7

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)

1
在签名中使用params={}是危险的,因为它具有可变性... - Daniel Böckenhoff
1
在签名中的params={}是危险的,因为它具有可变性... - undefined
空字典的默认参数本意是可变的,因为它用于将参数传递给请求而不是处理响应。如果这被认为是“危险”的话,请提供一个威胁模型的示例。 - undefined

4

HTTP协议无法处理"文件"和"目录"。请选择其他协议。


4
您可以使用以下脚本获取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")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接