我从MOOC中学到了很多东西,所以我想为这个目的回报他们一些东西。我正在考虑在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协议导致的错误还是我遗漏了什么?
我不想使用任何第三方库。
发布于 2014-09-26 22:16:39
我使用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-26 21:32:03
我认为你需要使用urllib2的HTTPBasicAuthHandler模块。检查“基本身份验证”部分。https://docs.python.org/2/howto/urllib2.html
我强烈建议您使用请求模块。它会让你的代码变得更好。http://docs.python-requests.org/en/latest/
https://stackoverflow.com/questions/26060712
复制相似问题