2017-12-31 190 views
0

私のFirefoxブラウザでは、ダウンロードサイトにログインし、そのクエリーボタンの1つをクリックします。小さなウィンドウが開き、「report1.csvを開く」という名前が付けられ、「開く」または「ファイルを保存」を選択できます。私はファイルを保存します。このアクションLive HTTP headersのために「Content-Disposition:attachment;」というWebページを取得できません。 python-requestsを使用して

は私を示しています

ます。https:// MYSERVER/ReportPage & NAMEをダウンロード= ALL & DATE = THISYEAR

GET/ReportPage = = ALL & DATEを& NAMEをダウンロードTHISYEAR HTTP/1.1
ホスト:myserverの
のUser-Agent:Mozillaの/ 5.0(X11; Linuxのx86_64で、RV:52.0)のGecko/20100101 Firefoxの/ 52.0
de-DE; q = 0.9、/; q = 0.8
Accept-Language:en-US、en; q = 0.8、de-DE; q = 0.5、デ; Q = 0.3
エンコーディングを受け入れ:、GZIPを収縮、
リファラーBRます。https:// MYSERVER/ReportPage 4 & NAME = ALL & DATE = THISYEAR
クッキー:JSESSIONID = 88DEDBC6880571FDB0E6E4112D71B7D6
接続?キープアライブ
アップグレード不安 - リクエスト:1

HTTP/1.1 200 OK
日付:土、2017年12月30日夜10時37分40秒GMT
サーバー:Apacheの-コヨーテ/ 1.1
最終-更新:土、2017年12月30日夜10時37分40秒GMT
が有効期限:木、1970年1月1日00 :00:00 GMT
プラグマ:no-cache
キャッシュコントロール:no-cache、no-store
コンテンツの処理:添付ファイル。 filename = "report1.csv";ファイル名* = UTF-8''report1.csv
のContent-Type:テキスト/ CSV
のContent-Length:332369
は、キープアライブ:= 5タイムアウト、最大= 100
接続:キープアライブ

これでリクエストをエミュレートしようとしています。

$ python3 
>>> import requests 
>>> from lxml import html 
>>> 
>>> s = requests.Session() 
>>> s.verify = './myserver.crt' # certificate of myserver for https 
>>> 
>>> # get the login web page to enter username and password 
... r = s.get('https://myserver') 
>>> 
>>> # Get url for logging in. It's the action-attribute in the form anywhere. 
... # We use xpath. 
... tree = html.fromstring(r.text) 
>>> loginUrl = 'https://myserver/' + list(tree.xpath("//form[@id='id4']/@action"))[0] 
>>> print(loginUrl) # it contains a session-id 
https://myserver/./;jsessionid=77EA70CB95252426439097E274286966?0-1.loginForm 
>>> 
>>> # logging in with username and password 
... r = s.post(loginUrl, data = {'username':'ingo','password':'mypassword'}) 
>>> print(r.status_code) 
200 
>>> # try to get the download file using url from Live HTTP headers 
... downloadQueryUrl = 'https://myserver/ReportPage?download&NAME=ALL&DATE=THISYEAR' 
>>> r = s.get(downloadQueryUrl) 
>>> print(r.status_code) 
200 
>>> print(r. headers) 
{'Connection': 'Keep-Alive', 
'Date': 'Sun, 31 Dec 2017 14:46:03 GMT', 
'Cache-Control': 'no-cache, no-store', 
'Keep-Alive': 'timeout=5, max=94', 
'Transfer-Encoding': 'chunked', 
'Expires': 'Thu, 01 Jan 1970 00:00:00 GMT', 
'Pragma': 'no-cache', 
'Content-Encoding': 'gzip', 
'Content-Type': 'text/html;charset=UTF-8', 
'Server': 'Apache-Coyote/1.1', 
'Vary': 'Accept-Encoding'} 
>>> print(r.url) 
https://myserver/ReportPage?4&NAME=ALL&DATE=THISYEAR 
>>> 

リクエストは成功しましたが、ファイルのダウンロードページが表示されません。 「Content-Disposition:attachment;」はありません。ヘッダーのエントリ。クエリの開始ページのみを取得します(例:リファラーからのページ

これはセッションクッキーと関連がありますか?リクエストが自動的にこれを管理しているようです。 csv-filesの特別な処理はありますか?ストリームを使用する必要がありますか? Live-HTTPヘッダーに表示されるダウンロードURLは正しいですか?たぶんダイナミックな創造がありますか?

「Content-Disposition:attachment;」というWebページを取得するにはどうすればよいですか? myserverからリクエストしてそのファイルをダウンロードしますか?

+0

多分あなたはいくつかのヘッダーを追加する必要はありません。 "User-Agent" – furas

+0

あなたは 'r.text'をチェックしましたか?たぶん有益な情報があるかもしれません。それは警告メッセージです。それをファイルに書き込んで、このファイルをブラウザで開くことができます。 – furas

+0

@furasこれを指摘してくれてありがとう。私はこれを試してみる。 – Ingo

答えて

0

私はそれを手に入れました。 @Patrick Mevzekは私を正しい方向に向ける。これありがとう。

ログイン後、私は最初にログインしたページにとどまりませんし、クエリを呼び出します。代わりに、私は、レポートページを要求し、そこからquery-urlを抽出し、query-urlを要求します。これで、ヘッダーに「Content-Disposition:attachment;」という応答が表示されます。テキストをstdoutに出力するのが簡単です。出力を任意のファイルにリダイレクトできるので、私はそれを好む。 Info-messagesはstderrに送られ、リダイレクトされた出力を混乱させません。典型的な電話は./download >out.csvです。

スクリプトテンプレートの完全性を確認するために、エラーチェックを行わずにスクリプトテンプレートを使用しています。

#!/usr/bin/python3 

import requests 
import sys 
from lxml import html 

s = requests.Session() 
s.verify = './myserver.crt' # certificate of myserver for https 

# get the login web site to enter username and password 
r = s.get('https://myserver') 

# Get url for logging in. It's the action-attribute in the form anywhere. 
# We use xpath. 
tree = html.fromstring(r.text) 
loginUrl = 'https://myserver/' + tree.xpath("//form[@id='id4']/@action")[0] 

# logging in with username and password and go to ReportPage with queries 
r = s.post(loginUrl, data = {'username':'ingo','password':'mypassword'}) 
queryUrl = 'https://myserver/ReportPage?NAME=ALL&DATE=THISYEAR' 
r = s.get(queryUrl) 

# Get the download link for this query from this site. It's a link anywhere 
# with value 'Download (UTF8)' 
tree = html.fromstring(r.text) 
downloadUrl = 'https://myserver/' + tree.xpath("//a[.='Download (UTF8)']/@href")[0] 

# get the download file 
r = s.get(downloadUrl) 
if r.headers.get('Content-Disposition'): 
    print('Downloading ...', file=sys.stderr) 
    print(r.text) 

# log out 
r = s.get('https://myserver/logout') 
関連する問題