5

我从 MOOCs 中学到了很多东西,所以我想给他们回馈一些东西,为此我正在考虑在 kivy 中设计一个小应用程序,因此需要 python 实现,实际上我想要实现的是登录到我的Coursera 帐户通过程序收集有关我目前正在学习的课程的信息,为此我首先必须登录到 coursera ( https://accounts.coursera.org/signin?post_redirect=https%3A%2F%2Fwww. coursera.org%2F),在搜索网络时,我遇到了这段代码:

import urllib2, cookielib, urllib

username = "abcdef@abcdef.com"      
password = "uvwxyz"

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'password' : password})
info = opener.open("https://accounts.coursera.org/signin",login_data)
for line in info:
    print line

以及一些类似的代码,但没有一个对我有用,每种方法都会导致我出现这种类型的错误:

Traceback (most recent call last):
  File "C:\Python27\Practice\web programming\coursera login.py", line 9, in <module>
    info = opener.open("https://accounts.coursera.org/signin",login_data)
  File "C:\Python27\lib\urllib2.py", line 410, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 404: Not Found

错误是由于 https 协议还是我遗漏了什么?

我不想使用任何 3rd 方库。

4

2 回答 2

2

requests为此目的使用它,我认为它是一个很棒的 python 库。这是一些示例代码,它是如何工作的:

import requests
from requests.auth import HTTPBasicAuth

credentials = HTTPBasicAuth('username', 'password')
response = requests.get("https://accounts.coursera.org/signin", auth=credentials)
print response.status_code
# if everything was fine then it prints
>>> 200

这是请求的链接:

http://docs.python-requests.org/en/latest/

于 2014-09-26T14:16:38.667 回答
1

我认为您需要HTTPBasicAuthHandler使用urllib2. 检查“基本身份验证”部分。https://docs.python.org/2/howto/urllib2.html

我强烈推荐你请求模块。它会让你的代码更好。http://docs.python-requests.org/en/latest/

于 2014-09-26T13:32:03.037 回答