【问题标题】:Python twill: download file accessible through PHP scriptPython twill:下载文件可通过 PHP 脚本访问
【发布时间】:2016-10-21 00:19:21
【问题描述】:

我使用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文件?

【问题讨论】:

  • 不完全是:在这种情况下,对网站的访问受密码保护。我需要发布一个登录表单。因此使用twill。 (我更喜欢使用requests,但似乎对登录标头进行了复杂的控制,经过多次尝试,我只能使用twill)。
  • 编辑:我编辑了我的问题:文件是 MS Excel 格式,不是 CSV,所以是二进制数据...
  • 如果您可以显示或阅读内容,这意味着您可以将其以您阅读的任何格式存储在您的终端 - 您可以使用 StringIO docs.python.org/2/library/stringio.html 或类似的作为您阅读的任何内容的中间存储和然后将其转换为 csv 。

标签: php python twill


【解决方案1】:

我设法将 cookie jar 从 twill 发送到 requests

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

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)

【讨论】:

  • 你从哪里得到get_browser()
【解决方案2】:

另一种使用twill.commands.save_html的方式修改为写为'wb'而不是'w':Python 2.7 using twill, saving downloaded file properly

【讨论】:

    猜你喜欢
    • 2015-03-24
    • 1970-01-01
    • 2011-09-25
    • 2020-10-15
    • 2021-08-15
    • 2011-02-10
    • 2022-11-28
    • 2011-05-12
    • 1970-01-01
    相关资源
    最近更新 更多