Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PythonTwill:下载可通过PHP脚本访问的文件_Php_Python_Twill - Fatal编程技术网

PythonTwill:下载可通过PHP脚本访问的文件

PythonTwill:下载可通过PHP脚本访问的文件,php,python,twill,Php,Python,Twill,我使用twill在受登录表单保护的网站上导航 from twill.commands import * go('http://www.example.com/login/index.php') fv("login_form", "identifiant", "login") fv("login_form", "password", "pass") formaction("login_form", "http://www.example.com/login/control.php") subm

我使用
twill
在受登录表单保护的网站上导航

from twill.commands import *

go('http://www.example.com/login/index.php') 
fv("login_form", "identifiant", "login")
fv("login_form", "password", "pass")
formaction("login_form", "http://www.example.com/login/control.php")
submit()
go('http://www.example.com/accueil/index.php')
在最后一页上,我想下载一个Excel文件,该文件可以通过
div
访问,并具有以下属性:

onclick="OpenWindowFull('../util/exports/control.php?action=export','export',200,100);"
通过
twill
我可以访问PHP脚本的URL并显示文件的内容

go('http://www.example.com/util/exports/control.php?action=export')
show()

但是,返回一个与原始内容对应的字符串:因此不可用。是否有类似于
urllib.urlretrieve()
的方法直接检索Excel文件?

我成功地将cookie jar从
twill
发送到
请求

注:我无法使用
请求
,只是因为登录时有一个复杂的控件(无法找出正确的标题或其他选项)


另一种使用
twill.commands.save_html
修改为写为“wb”而不是“w”的方法:

看起来与不完全相同:在这种情况下,访问网站的权限受密码保护。我需要发布一个登录表单。因此使用
twill
。(我更喜欢使用
请求
,但似乎有一个复杂的登录标题控制,经过多次尝试后,我只能使用
twill
)。编辑:我编辑了我的问题:文件是MS Excel格式,而不是CSV,所以二进制数据…如果你可以显示或读取内容,这意味着你可以将其以任何格式存储在你的终端上-你可以使用StringIO或类似的方法作为你所读取内容的中间存储,然后将其转换为csv。
import requests
from twill.commands import *

# showing login form with twill
go('http://www.example.com/login/index.php') 
showforms()

# posting login form with twill
fv("login_form", "identifiant", "login")
fv("login_form", "password", "pass")
formaction("login_form", "http://www.example.com/login/control.php")
submit()

# getting binary content with requests using twill cookie jar
cookies = requests.utils.dict_from_cookiejar(get_browser()._session.cookies)
url = 'http://www.example.com/util/exports/control.php?action=export'

with open('out.xls', 'wb') as handle:
    response = requests.get(url, stream=True, cookies=cookies)

    if not response.ok:
        raise Exception('Could not get file from ' + url)

    for block in response.iter_content(1024):
        handle.write(block)