Python列出HTTP文件和目录

apf*_*pfz 6 html python directory ip-address

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

使用urllib和其他人,我只能显示index.html文件的内容.但是,如果我想查看根目录中的哪些文件呢?

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

Ken*_*nly 25

使用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
Run Code Online (Sandbox Code Playgroud)


Ada*_*son 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)
Run Code Online (Sandbox Code Playgroud)

  • 由于可变性,签名中的 params={} 是危险的...... (2认同)

Ign*_*ams 6

HTTP不适用于"文件"和"目录".选择一个不同的协议.


jad*_*k94 5

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

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

现在,要实现您想要的功能,您必须使用HTTP之外的其他内容(您要访问的"IP地址"上的FTP服务器才能完成工作),或者在该计算机上设置HTTP服务器path(http://192.168.2.100/directory)其中的文件列表(以任何格式)并通过Python进行解析.

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