python urllib2,密码内容和空响应

标签 python request urllib2

我正在使用 URLlib2(和 python 2.7)从网站获取一些内容。到目前为止,我一直在使用 URLlib2 OK 来获取内容,但这是我第一次访问在内容级别有密码的网站。我有一个合法的 u:p (我显然不能在这里分享),而且似乎我没有以某种方式为我的请求提供正确的凭据。

我用过这里的方法:Python urllib2, basic HTTP authentication, and tr.im替换(username, password)将我的凭据作为字符串(“myUsername”,“myPassword”)

当我 print result.read()我得到一个空行,当我尝试 print result.headers() 时我得到:

<addinfourl at 40895752L whose fp = <socket._fileobject object at 0x00000000026757C8>>

例如,对于每个预期的调用实例,我认为这意味着那里有一个文件对象......

我试过print result.info()查看是否有标题返回,我看到一组标题:

REDACTED
Date: Mon, 01 Oct 2012 10:06:24 GMT
Server: Apache/2.2.3 (Red Hat)
X-Powered-By: PHP/5.1.6
Set-Cookie: OJSSID=mc7u47e674jmpjgk3kspfgc9l3; path=/
Refresh: 0; url=http:REDACTED loginMessage=reader.subscriptionRequiredLoginText
Content-Length: 0
Connection: close
Content-Type: text/html; charset=UTF-8

所以我可以从“loginMessage=reader.subscriptionRequiredLoginText”中得知我没有正确发送凭据。

有什么指点吗?

调用代码为:

def getArticle(newLink):
request = urllib2.Request(newLink)
base64string = base64.encodestring('%s:%s' % ("myUsername", "myPassword")).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)
print result.read()

示例 URL 为:已编辑 - 这不是我的网站!

最佳答案

您会发现处理 requests库比 urllib2 好得多。

查看您提供的链接,它不需要基本身份验证,而是一个表单...因此您需要获取表单的“action”属性的 URL,并向其提交数据。使用请求的示例:

import requests
url = 'http://www.content.alternative.ac.nz/index.php/alternative/login/signIn'
r = requests.post(url, data={'username': 'username', 'password': 'password', 'remember': '1'})

这个我无法完全检查(因为我没有有效的 u&p),但是通过有效发送并勾选“记住我”按钮,您应该可以通过 r.cookies 获得一个可访问的 cookie code> 这希望意味着可以用于进一步的请求,例如:

cookies = r.cookies
r = requests.get('http://www.content.alternative.ac.nz/index.php/alternative/article/view/176/202', cookies=cookies)

关于python urllib2,密码内容和空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12670944/

相关文章:

python - 如何删除 Countvectorizer 中存在的数字字符?

java - 检查连接 jpype - java

post - Google Drive REST API 分段上传。 400 : Bad content type. 请使用多部分

request - 如何从 Pyramid 中的 post 请求中检索 json 数据?

python - python urllib2 会自动解压缩从网页获取的 gzip 数据吗?

python urllib2 发布请求

python - 从 smg 文件 Beautiful Soup 和 Python 中提取正文标签

python - Django 一对一关系查询集

php - 获取站点发送给自身的 POST 请求?

python - 使用奇怪的编码从Python中的.txt url收集数据