LoginSignup
1
5

More than 5 years have passed since last update.

RequestsモジュールでWebDAVのファイル一覧を見たい

Posted at

Requests、便利ですよね。pythonのモジュールの中で一番良く使うと思います。urllib2の代わりに標準搭載してくれたらいいのに。

さて、WebDAVのファイル一覧を取得するためには、PROPFINDというメソッドを投げないといけないのですが、残念ながらrequestsではこれに対応していません。

requests.propfind('https://example.com')

などとやろうものなら、華麗にAttributeError: module 'requests' has no attribute 'propfind'と返してくれます。

代わりに、Requestsの低レベルAPIであるRequestSessionを用いて、PROPFINDメソッドを投げてみましょう。

import requests

def propfind(url):

    req = requests.Request('PROPFIND', url, headers={'Depth': '1'})
    prepped = req.prepare()

    s = requests.Session()
    resp = s.send(prepped)
    return resp.text

headers={'Depth': '1'}としているのは、WebDAV内の全リストを取得するとサーバ側に負荷が掛かる為、指定したURL直下のリストのみを取得するようにしています。
レスポンスはXMLですので、ElementTreeでたどっていきましょう。{DAV:}href属性を取得するだけです。
先ほど作ったpropfind(url)で取得したXMLを、次に作るxml_to_list(xml)に渡してみましょう。

import xml.etree.ElementTree as ET

def xml_to_list(xml):
    root = ET.fromstring(xml)

    files = [ f.text for f in root.findall('.//{DAV:}href') ]

    if (files):
        return files
    else:
        None

root.findall()の中の記法はXPathです。
これで、WebDAVのファイルリストがリストで戻ってきます。

参考

Advanced Usage(Requests公式)

1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5