Python twill:通过PHP脚本下载文件

3

我使用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文件,可以通过以下属性的
访问:
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文件?

看起来类似于https://dev59.com/ImQo5IYBdhLWcg3wI8nx。 - dmitryro
不是很准确:在这种情况下,网站的访问受到密码保护。我需要发布一个登录表单。因此使用twill。(我更喜欢使用requests,但似乎有一个复杂的控制登录头,并且经过多次尝试,我只能使用twill使其正常工作)。 - Antoine Gautier
编辑:我修改了我的问题:文件是MS Excel格式,而不是CSV,因此是二进制数据... - Antoine Gautier
如果您可以显示或读取内容,则意味着您可以以任何格式将其存储在本地 - 您可以使用StringIO https://docs.python.org/2/library/stringio.html或类似的中介存储器来存储您读取的任何内容,然后将其转换为csv。 - dmitryro
2个回答

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() 函数? - TheCrazyProfessor
曾经在这里 https://github.com/twill-tools/twill/blob/0f91a45652e2ea83b486562330677092b3f696c6/twill/commands.py#L13 ,但在此帖子之后进行了重构。不知道当前的 API 如何。 - Antoine Gautier

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接