http リクエストを作成するために、新しい Python Requests ライブラリを使用しています。サーバーからテキストとして Cookie を取得します。CookieJar
それをクッキーを含む に変えるにはどうすればよいですか?
10 に答える
私はこの質問に混乱しています。requests ライブラリは、Cookie を jar に入れます。
import requests
import cookielib
URL = '...whatever...'
jar = cookielib.CookieJar()
r = requests.get(URL, cookies=jar)
r = requests.get(URL, cookies=jar)
URL への最初の要求で、jar がいっぱいになります。2 番目の要求は、Cookie をサーバーに送り返します。同じことが標準ライブラリの urllib モジュールcookielibにも当てはまります。(ドキュメントは現在 2.x バージョンで利用可能)
あなたを助けるために、私はモジュール全体を書きました。個人の Web ページと Google の Cookie で試してみたので、うまくいくと思います。
How to add cookie to existing cookielib CookieJar instance in Python?から助けを得ました。
ここにはセミクラッジを含む多くの非Pythonicコードがあるため、マイレージは異なる場合があります。特に想定される項目 (ポート 80 など) を使用して、必要に応じて微調整してください。以下の引数としての「リクエスト」は requests.request 型であり、「メソッド」引数はすべて大文字でなければならないことに気付きました。私が助けてくれることを願っています!
注: 明確化のためにコメントを追加する時間がなかったので、ソースを使用する必要があります。
import Cookie,cookielib,requests,datetime,time #had this out but realized later I needed it when I continued testing
def time_to_tuple(time_string):
wday = {'Mon':0,'Tue':1,'Wed':2,'Thu':3,'Fri':4,'Sat':5,'Sun':6}
mon = {'Jan':1,'Feb':2,'Mar':3,'Apr':4,'May':5,'Jun':6,'Jul':7,'Aug':8,'Sep':9,'Oct':10,'Nov':11,'Dec':12}
info = time_string.split(' ')
info = [i.strip() for i in info if type(i)==str]
month = None
for i in info:
if '-' in i:
tmp = i.split('-')
for m in tmp:
try:
tmp2 = int(m)
if tmp2<31:
mday = tmp2
elif tmp2 > 2000:
year = tmp2
except:
for key in mon:
if m.lower() in key.lower():
month = mon[key]
elif ':' in i:
tmp = i.split(':')
if len(tmp)==2:
hour = int(tmp[0])
minute = int(tmp[1])
if len(tmp)==3:
hour = int(tmp[0])
minute = int(tmp[1])
second = int(tmp[2])
else:
for item in wday:
if ((i.lower() in item.lower()) or (item.lower() in i.lower())):
day = wday[item]
if month is None:
for item in mon:
if ((i.lower() in item.lower()) or (item.lower() in i.lower())):
month = mon[item]
return year,month,mday,hour,minute,second
def timefrom(year,month,mday,hour,minute,second):
time_now = time.gmtime()
datetime_now = datetime.datetime(time_now.tm_year,time_now.tm_mon,
time_now.tm_mday,time_now.tm_hour,
time_now.tm_min,time_now.tm_sec)
then = datetime.datetime(year,month,mday,hour,minute,second)
return (datetime_now-then).total_seconds()
def timeto(year,month,mday,hour,minute,second):
return -1*timefrom(year,month,mday,hour,minute,second)
##['comment', 'domain', 'secure', 'expires', 'max-age', 'version', 'path', 'httponly']
def parse_request(request):
headers = request.headers
cookieinfo = headers['set-cookie'].split(';')
name = 'Undefined'
port=80
port_specified=True
c = Cookie.SmartCookie(headers['set-cookie'])
cj = cookielib.CookieJar()
for m in c.values():
value = m.coded_value
domain = m['domain']
expires = m['expires']
if type(expires) == str:
tmp = time_to_tuple(expires)
expires = timeto(tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],tmp[5])
max_age=m['max-age']
version = m['version']
if version == '':
version = 0
path = m['path']
httponly = m['httponly']
if httponly == '':
if 'httponly' in headers['set-cookie'].lower():
httponly = True
else:
httponly = False
secure = m['secure']
comment=m['comment']
port = 80
port_specified=False
domain_specified=True
domain_initial_dot = domain.startswith('.')
path_specified=True
discard = True
comment_url=None
rest={'HttpOnly':httponly}
rfc2109=False
ck = cookielib.Cookie(version,name,value,port,port_specified,domain,
domain_specified,domain_initial_dot,path,path_specified,
secure,expires,discard,comment,comment_url,rest,rfc2109)
cj.set_cookie(ck)
return cj
cookielib.LWPCookieJar には load メソッドと save メソッドがあります。フォーマットを見て、それがネイティブ Cookie フォーマットと一致するかどうかを確認してください。StringIO を使用して、Cookie を直接 Cookie jar にロードできる可能性があります。あるいは、リクエストが内部で urllib2 を使用している場合、デフォルトのオープナーに Cookie ハンドラーを追加できませんか?
私は同じことをしようとしています。これは私がこれまでに持っているものであり、何らかの理由でヘッダーに Cookie を送信していません。ただし、問題を解決するのに十分な距離に到達する可能性があります。
import requests
import cookielib
import logging
log = logging.getLogger(__name__)
def auth(auth_url, cookies):
cj = cookielib.CookieJar()
for x in cookies:
if len(cookies[x]) > 0:
ck = cookielib.Cookie(version=1, name=x, value=cookies[x],
port=None, port_specified=False, domain='.example.com',
domain_specified=True,
domain_initial_dot=True, path='/',
path_specified=True, secure=False,
expires=None, discard=True,
comment=None, comment_url=None,
rest=None, rfc2109=True)
log.info(ck)
cj.set_cookie(ck)
log.info("cookies = %s " % cj)
response = requests.get(auth_url, cookies=cj)
log.info("response %s \n" % response)
log.info("response.headers %s \n" % response.headers)
log.info("response.content %s \n" % response.content)
url
あなたが要求し、あなたがheaders
応答として得たと仮定します。型の型url
は文字列です。型の型headers
はリストです。
import urllib2
import cookielib
class dummyResponse:
def __init__(self,headers):
self.headers=headers
def info(self):
return dummyInfo(self.headers)
class dummyInfo:
def __init__(self,headers):
self.headers=headers
def getheaders(self,key):
#Headers are in the form: 'Set-Cookie: key=val\r\n'. We want 'key=val'
newMatches=[]
for header in self.headers:
if header.lower().startswith(key.lower()):
clearHeader=header[len(key)+1:].strip()
newMatches.append(clearHeader)
return newMatches
req=urllib2.Request(url)
resp=dummyResponse(headers)
jar=cookielib.CookieJar()
jar.extract_cookies(resp, req)
このサイトを試してみてください: Voidspace の記事
何年にもわたって、この種のことを行うのに voidspace が非常に役立つことがわかりました。私はかなりの劣等生ですが、私が役に立てば幸いです。このコードは、Voidspace Recipes でソース コード .py として入手できますが、ダウンロード ファイルは「.py-」ファイルです。