【问题标题】:can't download cookie protected file with python无法使用 python 下载受 cookie 保护的文件
【发布时间】:2013-06-07 10:10:09
【问题描述】:

我整天都在寻求解决这个问题。 有这个http://www.some.site/index.php 正在请求用户和密码+发送cookie。好吧,我是这样进入的:

import urllib, urllib2, cookielib, os
import re # not required here but tried it out though
import requests # not required here but tried it out though
username = 'somebody'
password = 'somepass'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
resp = opener.open('http://www.some.site/index.php', login_data)
print resp.read()

问题在于屏幕中间有一个下载 .xls 文件的链接:http://www.some.site/excel_file.php?/t=1303457489。我可以在任何浏览器(Mozilla、Chrome、IE)中下载该文件,但不能使用 Python。在 .php 之后,发布数据(即: ?t=1370919996 )在我登录或刷新页面时一直在变化。

也许我错了,但我相信 Post Data 是从 cookie(或 session-cookie)生成的,但 cookie 只包含这个:('set-cookie', 'PHPSESSID=9cde55534fcc8e136fcf6588c0d0f1df; path=/')

这是我尝试保存文件的一种方式:

print "downloading with urllib2"
f = urllib2.urlopen('http://www.some.site/excel_file.php')
data = f.read()
with open("exceldoc.xls", "wb") as code:
    code.write(data)

如果我保存它或打印它会给出同样的错误请求错误:

<b>Fatal error</b>:  Call to a member function FetchRow() on a non-object in <b>http://www.some.site/excel_file.php</b> on line <b>112</b><br 

如何使用 Python 下载此文件? 非常感谢您的帮助!

有很多类似的帖子,我检查过它们,我的例子都是从这些帖子中得到启发的,但对我没有任何帮助。我对cookies、php、js不是很熟悉。

编辑:这是我打印出 index.php 的内容时得到的:

<html>
<head>
<title>SOMETITLE</title>
<meta http-equiv="Page-Enter" content="blendTrans(Duration=0.5)">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel='stylesheet' type='text/css' href='somesite.css'>
<SCRIPT LANGUAGE="JavaScript">
<!-- JavaScript hiding

function clearDefault(obj) {
    if (!obj._cleared) {
                obj.value='';
                obj._cleared=true;
    }
}

// -->
</SCRIPT>
</head>

<body bgcolor="#FFFFFF" text="#000000">

<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td>
      <table width="1000" height="150" border="0" align="center" cellpadding="16" cellspacing="0" class="header" style="background: #989896 url('images/header.png') no-repeat;">
        <tr>
          <td valign="middle">
            <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
              <tr>
                <td width="380">&nbsp;</td>
                <td>
                  <div id="login">
                       <form name="flogin" method="post" action="/index.php">
                      <h1>Login</h1>
                      <input name="uName" type="text" value="Username:" class="name" onfocus="clearDefault(this)">
                      <br>
                      <input type="password" name="uPw"  value="Password:" class="pass" onfocus="clearDefault(this)">
                      <input type="submit" name="Submit" value="OK" class="submit">
                    </form>
                  </div>                                                                
                                                                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
                </td>
  </tr>
</table>

</body>
</html>

【问题讨论】:

  • 通过发布数据您的意思是 t= GET 参数?这看起来是一个 unix 时间戳(导入时间;time.time()),也许有帮助?
  • 是的,我所说的发布数据是指 ?t=1322376525 的东西,它一直在变化。我已经检查了该网站的源代码。没有帮助,或者我无法解释。
  • @Blubber 它是 unix 时间戳。我已经设法转换它,但至少我知道那是什么,我不知道它是否有任何其他帮助。我尝试用它调用文件:D

标签: python cookies download session-cookies urllib2


【解决方案1】:

您可以尝试解析来自第一个代码部分的响应,并将提取的 url 与相同的opener 一起使用。在不知道链接的实际格式的情况下:

import urllib, urllib2, cookielib, os
import re # going to use this now!

username = 'somebody'
password = 'somepass'

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
resp = opener.open('http://www.some.site/index.php', login_data)
content = resp.read()
print content

match = re.search(
    r"<a\s+href=\"(?P<file_link>http://www.some.site/excel_file.php?t=\d+)\">",
    content,
    re.IGNORECASE
)

assert match is not None, "Couldn't find the file link..."

file_link = match.group('file_link')
print "downloading {} with urllib2".format(file_link)
f = opener.open(file_link)
data = f.read()
with open("exceldoc.xls", "wb") as code:
    code.write(data)

【讨论】:

  • 问题是第一个代码段没有提取链接。我认为它隐藏在javascript中。任何进一步的想法?到目前为止,我感谢您的努力。
  • @Laci 不看内容就不多说了。你确定t 是必需的吗?您是否尝试过 cmets 中有关创建自己的时间戳并使用它的建议?您是否尝试过合并 2 个代码段并为两者使用相同的 opener 而不是 urllib2.urlopen 以便重复使用 cookie?
  • 感谢您的快速回复。我已经用 index.php 的内容更新了问题(在您的解决方案中首次打印)。不幸的是,我得到:Traceback (most recent call last): File "C:/Python27/filexample.py", line 16, in &lt;module&gt; assert match is not None, "Couldn't find the file link..." AssertionError: Couldn't find the file link...
  • @Laci,这只是意味着正则表达式找不到链接
  • @Laci,我看到了你的编辑。你确定你登录成功了吗?如果你看到了,我猜想登录没有用。通常,您要么被重定向到不同的页面,要么在成功登录后至少会呈现不同的内容......从源头看起来你需要将{'username' : username, 'j_password' : password}更改为{'uName' : username, 'uPw' : password}
猜你喜欢
  • 1970-01-01
  • 2012-12-23
  • 1970-01-01
  • 1970-01-01
  • 2019-03-23
  • 1970-01-01
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多