gpt4 book ai didi

python cookielib 错误 :403 Forbidden

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:23:49 26 4
gpt4 key购买 nike

我正在学习 python 网络。我已经学习了套接字,现在我想学习 python HTTP 来连接到 HTTPServer,提取 cookie 等。我面临着提取 cookie 的问题。尝试谷歌但没有找到解决方案,这是代码:

import cookielib
import urllib
import urllib2

ID_USERNAME= 'id_username'
ID_PASSWORD = 'id_password'
USERNAME = 'you@email.com'
PASSWORD = 'mypassword'
LOGIN_URL = 'https://bitbucket.org/account/signin/?next=/'
NORMAL_URL = 'https://bitbucket.org/'

def extract_cookie_info():
cj=cookielib.CookieJar()
login_data= urllib.urlencode({ID_USERNAME : USERNAME,ID_PASSWORD:PASSWORD})
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
resp = opener.open(LOGIN_URL,login_data)
for cookie in cj:
print "First time cookie: %s ----> %s" %(cookie.name,cookie.value)
print "Headers: %s"%resp.headers
resp = opener.open(NORMAL_URL)
for cookie in cj:
print "Second time cookie: %s --> %s"%(cookie.name,cookie.value)
print "Headers : %s"%resp.headers


if __name__ == '__main__':
extract_cookie_info()

这是错误:

Traceback (most recent call last):
File "e.py",line 27,in <module>
extract_cookie_info()
File "e.py",line 16,in extract_cookie_info
resp=opener.open(LOGIN_URL,login_data)
File "C:\Python27\lib\urllib2.py",line 435, in open
response = meth(req,response)
File "C:\Python27\lib\urllib2.py", line 548, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python27\lib\urllib2.py", line 473, in error
return self._call_chain(*args)
File "C:\Python27\lib\urllib2.py", line 407, in _call_chain
result = func(*args)
File "C:\Python27\lib\urllib2.py", line 556, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden

最佳答案

您将以 POST 数据而不是 url 的一部分发送您的登录详细信息。

>>> url = 'https://bitbucket.org/account/signin/'
>>> user = 'foo@example.com'
>>> pwd = 'secret'
>>> d = urlencode({'ID_USERNAME': user, 'ID_PASSWORD': pwd})
>>> cj = cookielib.CookieJar()
>>> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
>>> resp = opener.open(url + '?' + d)
>>> res.getcode()
200
>>> for cookie in cj:print cookie.name
...
csrftoken

关于python cookielib 错误 :403 Forbidden,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48005772/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com