http.cookiejar --- HTTP クライアント用の Cookie 処理¶
ソースコード: Lib/http/cookiejar.py
The http.cookiejar module defines classes for automatic handling of HTTP
cookies. It is useful for accessing websites that require small pieces of data
-- cookies -- to be set on the client machine by an HTTP response from a
web server, and then returned to the server in later HTTP requests.
Both the regular Netscape cookie protocol and the protocol defined by
RFC 2965 are handled. RFC 2965 handling is switched off by default.
RFC 2109 cookies are parsed as Netscape cookies and subsequently treated
either as Netscape or RFC 2965 cookies according to the 'policy' in effect.
Note that the great majority of cookies on the internet are Netscape cookies.
http.cookiejar attempts to follow the de-facto Netscape cookie protocol (which
differs substantially from that set out in the original Netscape specification),
including taking note of the max-age and port cookie-attributes
introduced with RFC 2965.
注釈
The various named parameters found in Set-Cookie and
Set-Cookie2 headers (for example, domain and expires) are
conventionally referred to as attributes. To distinguish them from
Python attributes, the documentation for this module uses the term
cookie-attribute instead.
このモジュールは以下の例外を定義しています:
- exception http.cookiejar.LoadError¶
この例外は
FileCookieJarインスタンスがファイルからクッキーを読み込むのに失敗した場合に発生します。LoadErrorはOSErrorのサブクラスです。
以下のクラスが提供されています:
- class http.cookiejar.CookieJar(policy=None)¶
policy は
CookiePolicyインターフェイスを実装するオブジェクトです。CookieJarクラスには HTTP クッキーを保管します。これは HTTP リクエストに応じてクッキーを取り出し、それを HTTP レスポンスの中で返します。必要に応じて、CookieJarインスタンスは保管されているクッキーを自動的に破棄します。このサブクラスは、クッキーをファイルやデータベースに格納したり取り出したりする操作をおこなう役割を負っています。
- class http.cookiejar.FileCookieJar(filename=None, delayload=None, policy=None)¶
policy は
CookiePolicyインターフェイスを実装するオブジェクトです。これ以外の引数については、該当する属性の説明を参照してください。FileCookieJarはディスク上のファイルからのクッキーの読み込み、もしくは書き込みをサポートします。実際には、load()またはrevert()のどちらかのメソッドが呼ばれるまでクッキーは指定されたファイルからはロード されません 。このクラスのサブクラスは FileCookieJar のサブクラスと web ブラウザとの連携 節で説明します。これは直接初期化されるべきではありません。以下のサブクラスを代わりに使用してください。
バージョン 3.8 で変更: filename 引数が path-like object を受け付けるようになりました。
- class http.cookiejar.CookiePolicy¶
このクラスは、あるクッキーをサーバから受け入れるべきか、そしてサーバに返すべきかを決定する役割を負っています。
- class http.cookiejar.DefaultCookiePolicy(blocked_domains=None, allowed_domains=None, netscape=True, rfc2965=False, rfc2109_as_netscape=None, hide_cookie2=False, strict_domain=False, strict_rfc2965_unverifiable=True, strict_ns_unverifiable=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal, strict_ns_set_initial_dollar=False, strict_ns_set_path=False, secure_protocols=('https', 'wss'))¶
Constructor arguments should be passed as keyword arguments only. blocked_domains is a sequence of domain names that we never accept cookies from, nor return cookies to. allowed_domains if not
None, this is a sequence of the only domains for which we accept and return cookies. secure_protocols is a sequence of protocols for which secure cookies can be added to. By default https and wss (secure websocket) are considered secure protocols. For all other arguments, see the documentation forCookiePolicyandDefaultCookiePolicyobjects.DefaultCookiePolicyimplements the standard accept / reject rules for Netscape and RFC 2965 cookies. By default, RFC 2109 cookies (that is, cookies received in a Set-Cookie header with a version cookie-attribute of 1) are treated according to the RFC 2965 rules. However, if RFC 2965 handling is turned off orrfc2109_as_netscapeisTrue, RFC 2109 cookies are 'downgraded' by theCookieJarinstance to Netscape cookies, by setting theversionattribute of theCookieinstance to 0.DefaultCookiePolicyalso provides some parameters to allow some fine-tuning of policy.
- class http.cookiejar.Cookie¶
This class represents Netscape, RFC 2109 and RFC 2965 cookies. It is not expected that users of
http.cookiejarconstruct their ownCookieinstances. Instead, if necessary, callmake_cookies()on aCookieJarinstance.
参考
urllib.requestモジュールクッキーの自動処理をおこない URL を開くモジュールです。
http.cookiesモジュールHTTP cookie classes, principally useful for server-side code. The
http.cookiejarandhttp.cookiesmodules do not depend on each other.- https://curl.se/rfc/cookie_spec.html
The specification of the original Netscape cookie protocol. Though this is still the dominant protocol, the 'Netscape cookie protocol' implemented by all the major browsers (and
http.cookiejar) only bears a passing resemblance to the one sketched out incookie_spec.html.- RFC 2109 - HTTP State Management Mechanism
RFC 2965 によって過去の遺物になりました。 Set-Cookie の version=1 で使います。
- RFC 2965 - HTTP State Management Mechanism
Netscape プロトコルのバグを修正したものです。 Set-Cookie のかわりに Set-Cookie2 を使いますが、普及してはいません。
- https://kristol.org/cookie/errata.html
RFC 2965 に対する未完の正誤表です。
RFC 2964 - Use of HTTP State Management
CookieJar and FileCookieJar objects¶
CookieJar オブジェクトは保管されている Cookie オブジェクトをひとつずつ取り出すための、 イテレータ プロトコルをサポートしています。
CookieJar は以下のようなメソッドを持っています:
- CookieJar.add_cookie_header(request)¶
request に正しい Cookie ヘッダを追加します。
If policy allows (that is, the
rfc2965andhide_cookie2attributes of theCookieJar'sCookiePolicyinstance are true and false respectively), the Cookie2 header is also added when appropriate.The request object (usually a
urllib.request.Requestinstance) must support the methodsget_full_url(),has_header(),get_header(),header_items(),add_unredirected_header()and the attributeshost,type,unverifiableandorigin_req_hostas documented byurllib.request.バージョン 3.3 で変更: request object needs
origin_req_hostattribute. Dependency on a deprecated methodget_origin_req_host()has been removed.
- CookieJar.extract_cookies(response, request)¶
HTTP response からクッキーを取り出し、ポリシーによって許可されていればこれを
CookieJar内に保管します。CookieJarは response 引数の中から許可されている Set-Cookie および Set-Cookie2 ヘッダを探しだし、適切に (CookiePolicy.set_ok()メソッドの承認におうじて) クッキーを保管します。The response object (usually the result of a call to
urllib.request.urlopen(), or similar) should support aninfo()method, which returns anemail.message.Messageinstance.The request object (usually a
urllib.request.Requestinstance) must support the methodget_full_url()and the attributeshost,unverifiableandorigin_req_host, as documented byurllib.request. The request is used to set default values for cookie-attributes as well as for checking that the cookie is allowed to be set.バージョン 3.3 で変更: request object needs
origin_req_hostattribute. Dependency on a deprecated methodget_origin_req_host()has been removed.
- CookieJar.set_policy(policy)¶
使用する
CookiePolicyインスタンスを指定します。
- CookieJar.make_cookies(response, request)¶
response オブジェクトから得られた
Cookieオブジェクトからなるシーケンスを返します。response および request 引数で要求されるインスタンスについては、
extract_cookies()の説明を参照してください。
- CookieJar.clear([domain[, path[, name]]])¶
いくつかのクッキーを消去します。
引数なしで呼ばれた場合は、すべてのクッキーを消去します。引数がひとつ与えられた場合、その domain に属するクッキーのみを消去します。ふたつの引数が与えられた場合、指定された domain と URL path に属するクッキーのみを消去します。引数が 3つ与えられた場合、domain, path および name で指定されるクッキーが消去されます。
与えられた条件に一致するクッキーがない場合は
KeyErrorを発生させます。
- CookieJar.clear_session_cookies()¶
すべてのセッションクッキーを消去します。
Discards all contained cookies that have a true
discardattribute (usually because they had either nomax-ageorexpirescookie-attribute, or an explicitdiscardcookie-attribute). For interactive browsers, the end of a session usually corresponds to closing the browser window.Note that the
save()method won't save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument.
さらに FileCookieJar は以下のようなメソッドを実装しています:
- FileCookieJar.save(filename=None, ignore_discard=False, ignore_expires=False)¶
クッキーをファイルに保存します。
この基底クラスは
NotImplementedErrorを発生させます。サブクラスはこのメソッドを実装しないままにしておいてもかまいません。filename is the name of file in which to save cookies. If filename is not specified,
self.filenameis used (whose default is the value passed to the constructor, if any); ifself.filenameisNone,ValueErroris raised.ignore_discard : 破棄されるよう指示されていたクッキーでも保存します。ignore_expires : 期限の切れたクッキーでも保存します。
ここで指定されたファイルがもしすでに存在する場合は上書きされるため、以前にあったクッキーはすべて消去されます。保存したクッキーはあとで
load()またはrevert()メソッドを使って復元することができます。
- FileCookieJar.load(filename=None, ignore_discard=False, ignore_expires=False)¶
ファイルからクッキーを読み込みます。
それまでのクッキーは新しいものに上書きされない限り残ります。
ここでの引数の値は
save()と同じです。名前のついたファイルはこのクラスがわかるやり方で指定する必要があります。さもないと
LoadErrorが発生します。さらに、例えばファイルが存在しないような時にOSErrorが発生する場合があります。
- FileCookieJar.revert(filename=None, ignore_discard=False, ignore_expires=False)¶
すべてのクッキーを破棄し、保存されているファイルから読み込み直します。
revert()はload()と同じ例外を発生させる事ができます。失敗した場合、オブジェクトの状態は変更されません。
FileCookieJar インスタンスは以下のような公開の属性をもっています:
- FileCookieJar.filename¶
クッキーを保存するデフォルトのファイル名を指定します。この属性には代入することができます。
- FileCookieJar.delayload¶
真であれば、クッキーを読み込むさいにディスクから遅延読み込みします。この属性には代入することができません。この情報は単なるヒントであり、 (ディスク上のクッキーが変わらない限りは) インスタンスのふるまいには影響を与えず、パフォーマンスのみに影響します。
CookieJarオブジェクトはこの値を無視することもあります。標準ライブラリに含まれているFileCookieJarクラスで遅延読み込みをおこなうものはありません。
FileCookieJar のサブクラスと web ブラウザとの連携¶
クッキーの読み書きのために、以下の CookieJar サブクラスが提供されています。
- class http.cookiejar.MozillaCookieJar(filename=None, delayload=None, policy=None)¶
Mozilla の
cookies.txtファイル形式 (この形式はまた curl や Lynx と Netscape ブラウザによっても使われています) でディスクにクッキーを読み書きするためのFileCookieJarです。注釈
このクラスは RFC 2965 クッキーに関する情報を失います。また、より新しいか、標準でない
portなどのクッキー属性についての情報も失います。警告
もしクッキーの損失や欠損が望ましくない場合は、クッキーを保存する前にバックアップを取っておくようにしてください (ファイルへの読み込み / 保存をくり返すと微妙な変化が生じる場合があります)。
また、Mozilla の起動中にクッキーを保存すると、Mozilla によって内容が破壊されてしまうことにも注意してください。
- class http.cookiejar.LWPCookieJar(filename=None, delayload=None, policy=None)¶
libwww-perl のライブラリである
Set-Cookie3ファイル形式でディスクにクッキーを読み書きするためのFileCookieJarです。これはクッキーを人間に可読な形式で保存するのに向いています。バージョン 3.8 で変更: filename 引数が path-like object を受け付けるようになりました。
CookiePolicy objects¶
CookiePolicy インターフェイスを実装するオブジェクトは以下のようなメソッドを持っています:
- CookiePolicy.set_ok(cookie, request)¶
クッキーがサーバから受け入れられるべきかどうかを表わす boolean 値を返します。
cookie は
Cookieインスタンスです。 request はCookieJar.extract_cookies()の説明で定義されているインターフェイスを実装するオブジェクトです。
- CookiePolicy.return_ok(cookie, request)¶
クッキーがサーバに返されるべきかどうかを表わす boolean 値を返します。
cookie は
Cookieインスタンスです。 request はCookieJar.add_cookie_header()の説明で定義されているインターフェイスを実装するオブジェクトです。
- CookiePolicy.domain_return_ok(domain, request)¶
与えられたクッキーのドメインに対して、そこにクッキーを返すべきでない場合には
Falseを返します。このメソッドは高速化のためのものです。これにより、すべてのクッキーをある特定のドメインに対してチェックする (これには多数のファイル読みこみを伴なう場合があります) 必要がなくなります。
domain_return_ok()およびpath_return_ok()の両方から true が返された場合、すべての決定はreturn_ok()に委ねられます。もし、このクッキードメインに対して
domain_return_ok()が true を返すと、つぎにそのクッキーのパス名に対してpath_return_ok()が呼ばれます。そうでない場合、そのクッキードメインに対するpath_return_ok()およびreturn_ok()は決して呼ばれることはありません。path_return_ok()が true を返すと、return_ok()がそのCookieオブジェクト自身の全チェックのために呼ばれます。そうでない場合、そのクッキーパス名に対するreturn_ok()は決して呼ばれることはありません。注意:
domain_return_ok()は request ドメインだけではなく、すべての cookie ドメインに対して呼ばれます。たとえば request ドメインが"www.example.com"だった場合、この関数は".example.com"および"www.example.com"の両方に対して呼ばれることがあります。同じことはpath_return_ok()にもいえます。request 引数は
return_ok()で説明されているとおりです。
- CookiePolicy.path_return_ok(path, request)¶
与えられたクッキーのパス名に対して、そこにクッキーを返すべきでない場合には
Falseを返します。domain_return_ok()の説明を参照してください。
上のメソッドの実装にくわえて、 CookiePolicy インターフェイスの実装では以下の属性を設定する必要があります。これはどのプロトコルがどのように使われるべきかを示すもので、これらの属性にはすべて代入することが許されています。
- CookiePolicy.netscape¶
Netscape プロトコルを実装していることを示します。
- CookiePolicy.hide_cookie2¶
Cookie2 ヘッダをリクエストに含めないようにします (このヘッダが存在する場合、私たちは RFC 2965 クッキーを理解するということをサーバに示すことになります)。
もっとも有用な方法は、 DefaultCookiePolicy をサブクラス化した CookiePolicy クラスを定義して、いくつか (あるいはすべて) のメソッドをオーバーライドすることでしょう。 CookiePolicy 自体はどのようなクッキーも受け入れて設定を許可する「ポリシー無し」ポリシーとして使うこともできます (これが役に立つことはあまりありませんが)。
DefaultCookiePolicy objects¶
クッキーを受けつけ、またそれを返す際の標準的なルールを実装します。
RFC 2965 クッキーと Netscape クッキーの両方に対応しています。デフォルトでは、RFC 2965 の処理はオフになっています。
自分のポリシーを提供するいちばん簡単な方法は、このクラスを継承して、自分用の追加チェックの前にオーバーライドした元のメソッドを呼び出すことです:
import http.cookiejar
class MyCookiePolicy(http.cookiejar.DefaultCookiePolicy):
def set_ok(self, cookie, request):
if not http.cookiejar.DefaultCookiePolicy.set_ok(self, cookie, request):
return False
if i_dont_want_to_store_this_cookie(cookie):
return False
return True
CookiePolicy インターフェイスを実装するのに必要な機能に加えて、このクラスではクッキーを受けとったり設定したりするドメインを許可したり拒絶したりできるようになっています。ほかにも、 Netscape プロトコルのかなり緩い規則をややきつくするために、いくつかの厳密性のスイッチがついています (いくつかの良性クッキーをブロックする危険性もありますが)。
A domain blocklist and allowlist is provided (both off by default). Only domains
not in the blocklist and present in the allowlist (if the allowlist is active)
participate in cookie setting and returning. Use the blocked_domains
constructor argument, and blocked_domains() and
set_blocked_domains() methods (and the corresponding
argument and methods for allowed_domains). If you set an allowlist, you can
turn it off again by setting it to None.
拒否あるいは許可リスト中にあるドメインのうち、ドット (.) で始まっていないものは、正確にそれと一致するドメインのクッキーにしか適用されません。たとえば拒否リスト中のエントリ "example.com" は、"example.com" にはマッチしますが、"www.example.com" にはマッチしません。一方ドット (.) で始まっているドメインは、より特化されたドメインともマッチします。たとえば、".example.com" は、"www.example.com" と "www.coyote.example.com" の両方にマッチします (が、"example.com" 自身にはマッチしません)。IP アドレスは例外で、つねに正確に一致する必要があります。たとえば、blocked_domains が "192.168.1.2" と ".168.1.2" を含んでいるとすると、192.168.1.2 はブロックされますが、193.168.1.2 はブロックされません。
DefaultCookiePolicy は以下のような追加メソッドを実装しています:
- DefaultCookiePolicy.blocked_domains()¶
ブロックしているドメインのシーケンスを (タプルとして) 返します。
- DefaultCookiePolicy.set_blocked_domains(blocked_domains)¶
ブロックするドメインを設定します。
- DefaultCookiePolicy.is_blocked(domain)¶
domain がクッキーを授受しない拒否リストに載っていれば
Trueを返します。
- DefaultCookiePolicy.allowed_domains()¶
Return
None, or the sequence of allowed domains (as a tuple).
- DefaultCookiePolicy.set_allowed_domains(allowed_domains)¶
Set the sequence of allowed domains, or
None.
- DefaultCookiePolicy.is_not_allowed(domain)¶
domain がクッキーを授受する許可リストに載っていれば
Trueを返します。
DefaultCookiePolicy インスタンスは以下の属性をもっています。これらはすべてコンストラクタから同じ名前の引数をつかって初期化することができ、代入してもかまいません。
- DefaultCookiePolicy.rfc2109_as_netscape¶
If true, request that the
CookieJarinstance downgrade RFC 2109 cookies (that is, cookies received in a Set-Cookie header with a version cookie-attribute of 1) to Netscape cookies by setting the version attribute of theCookieinstance to 0. The default value isNone, in which case RFC 2109 cookies are downgraded if and only if RFC 2965 handling is turned off. Therefore, RFC 2109 cookies are downgraded by default.
一般的な厳密性のスイッチ:
- DefaultCookiePolicy.strict_domain¶
サイトに、国別コードとトップレベルドメインだけからなるドメイン名 (
.co.uk,.gov.uk,.co.nzなど) を設定させないようにします。これは完璧からはほど遠い実装であり、いつもうまくいくとは限りません!
RFC 2965 プロトコルの厳密性に関するスイッチ:
- DefaultCookiePolicy.strict_rfc2965_unverifiable¶
検証不可能なトランザクション (通常これはリダイレクトか、別のサイトがホスティングしているイメージの読み込み要求です) に関する RFC 2965 の規則に従います。この値が偽の場合、検証可能性を基準にしてクッキーがブロックされることは 決して ありません
Netscape プロトコルの厳密性に関するスイッチ:
- DefaultCookiePolicy.strict_ns_unverifiable¶
検証不可能なトランザクションに関する RFC 2965 の規則を Netscape クッキーに対しても適用します。
- DefaultCookiePolicy.strict_ns_domain¶
Netscape クッキーに対するドメインマッチングの規則をどの程度厳しくするかを指示するフラグです。とりうる値については下の説明を見てください。
- DefaultCookiePolicy.strict_ns_set_initial_dollar¶
Set-Cookie: ヘッダで、
'$'で始まる名前のクッキーを無視します。
- DefaultCookiePolicy.strict_ns_set_path¶
要求した URI にパスがマッチしないクッキーの設定を禁止します。
strict_ns_domain is a collection of flags. Its value is constructed by
or-ing together (for example, DomainStrictNoDots|DomainStrictNonDomain means
both flags are set).
- DefaultCookiePolicy.DomainStrictNoDots¶
When setting cookies, the 'host prefix' must not contain a dot (for example,
www.foo.bar.comcan't set a cookie for.bar.com, becausewww.foocontains a dot).
- DefaultCookiePolicy.DomainStrictNonDomain¶
Cookies that did not explicitly specify a
domaincookie-attribute can only be returned to a domain equal to the domain that set the cookie (for example,spam.example.comwon't be returned cookies fromexample.comthat had nodomaincookie-attribute).
以下の属性は上記のフラグのうちもっともよく使われる組み合わせで、便宜をはかるために提供されています:
- DefaultCookiePolicy.DomainLiberal¶
Equivalent to 0 (that is, all of the above Netscape domain strictness flags switched off).
- DefaultCookiePolicy.DomainStrict¶
DomainStrictNoDots|DomainStrictNonDomainと同じです。
Cookie objects¶
Cookie instances have Python attributes roughly corresponding to the
standard cookie-attributes specified in the various cookie standards. The
correspondence is not one-to-one, because there are complicated rules for
assigning default values, because the max-age and expires
cookie-attributes contain equivalent information, and because RFC 2109 cookies
may be 'downgraded' by http.cookiejar from version 1 to version 0 (Netscape)
cookies.
CookiePolicy メソッド内でのごくわずかな例外を除けば、これらの属性に代入する必要はないはずです。このクラスは内部の一貫性を保つようにはしていないため、代入するのは自分のやっていることを理解している場合のみにしてください。
- Cookie.version¶
Integer or
None. Netscape cookies haveversion0. RFC 2965 and RFC 2109 cookies have aversioncookie-attribute of 1. However, note thathttp.cookiejarmay 'downgrade' RFC 2109 cookies to Netscape cookies, in which caseversionis 0.
- Cookie.name¶
クッキーの名前 (文字列)。
- Cookie.value¶
Cookie value (a string), or
None.
- Cookie.port¶
String representing a port or a set of ports (for example, '80', or '80,8080'), or
None.
- Cookie.domain¶
クッキーのドメイン (文字列) 。
- Cookie.path¶
Cookie path (a string, for example,
'/acme/rocket_launchers').
- Cookie.secure¶
そのクッキーを返せるのがセキュアな接続のみならば
Trueを返します。
- Cookie.expires¶
Integer expiry date in seconds since epoch, or
None. See also theis_expired()method.
- Cookie.discard¶
これがセッションクッキーであれば
Trueを返します。
- Cookie.comment¶
String comment from the server explaining the function of this cookie, or
None.
- Cookie.comment_url¶
URL linking to a comment from the server explaining the function of this cookie, or
None.
- Cookie.rfc2109¶
Trueif this cookie was received as an RFC 2109 cookie (that is, the cookie arrived in a Set-Cookie header, and the value of the Version cookie-attribute in that header was 1). This attribute is provided becausehttp.cookiejarmay 'downgrade' RFC 2109 cookies to Netscape cookies, in which caseversionis 0.
- Cookie.port_specified¶
サーバがポート、あるいはポートの集合を (Set-Cookie / Set-Cookie2 ヘッダ内で) 明示的に指定していれば
Trueを返します。
- Cookie.domain_specified¶
サーバにより明示的にドメインが指定されていれば
Trueを返します。
- Cookie.domain_initial_dot¶
サーバが明示的に指定したドメインがドット (
'.') で始まっていればTrueを返します。
クッキーは、オプションとして標準的でないクッキー属性を持つこともできます。これらは以下のメソッドでアクセスできます:
- Cookie.has_nonstandard_attr(name)¶
そのクッキーが指定された名前のクッキー属性をもっている場合には
Trueを返します。
- Cookie.get_nonstandard_attr(name, default=None)¶
クッキーが指定された名前のクッキー属性をもっていれば、その値を返します。そうでない場合は default を返します。
- Cookie.set_nonstandard_attr(name, value)¶
指定された名前のクッキー属性を設定します。
Cookie クラスは以下のメソッドも定義しています:
- Cookie.is_expired(now=None)¶
サーバが要求するクッキーの有効期限を過ぎていれば
Trueを返します。 now が (エポックからの経過秒で) 指定されているときは、特定の時刻で期限切れかどうかを判定します。
使用例¶
The first example shows the most common usage of http.cookiejar:
import http.cookiejar, urllib.request
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
以下の例では、URL を開く際に Netscape や Mozilla または Lynx のクッキーを使う方法を示しています (クッキーファイルの位置は Unix/Netscape の慣例にしたがうものと仮定しています):
import os, http.cookiejar, urllib.request
cj = http.cookiejar.MozillaCookieJar()
cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt"))
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
つぎの例は DefaultCookiePolicy の使用例です。 RFC 2965 クッキーをオンにし、Netscape クッキーを設定したり返したりするドメインに対してより厳密な規則を適用します。そしていくつかのドメインからクッキーを設定あるいは返還するのをブロックしています:
import urllib.request
from http.cookiejar import CookieJar, DefaultCookiePolicy
policy = DefaultCookiePolicy(
rfc2965=True, strict_ns_domain=Policy.DomainStrict,
blocked_domains=["ads.net", ".ads.net"])
cj = CookieJar(policy)
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")