php - python 纹 : download file accessible through PHP script

标签 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")
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 发送到 requests

注意:我无法使用 requests 只是因为登录时的复杂控制(无法找出正确的 header 或其他选项)。

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)

关于php - python 纹 : download file accessible through PHP script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37910736/

相关文章:

javascript - 从从 JQuery 调用的文件中使用 AJAX 调用文件

Python 迭代工作表并删除列

Python:单击带有 urllib 或 urllib2 的按钮

python - 如何将行和列添加到 NUMPY 数组?

python - 使用 Python 或 Django 处理收到的电子邮件?

python - 如何配置Python Twill/Mechanize库来访问Facebook

python - 斜纹/机械化访问 html 内容

php - 一个 MySQL 插入生成 3 行而不是 1 行

php - 将两个 mySQL sum 查询合并为一个使用不同 where 子句的查询

php - 在 PHP 中,我可以区分 intval(null) 和 intval ("0") 的结果吗?