新答案
好吧,所以我还是不知道你到底想达到什么目的。
如果您想从requests.RequestCookieJar对象中提取原始url(这样您就可以检查是否与给定的子域匹配),这是(据我所知)不可能的。
不过,你也可以做些类似的事情:#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import requests
import re
class getCookies():
def __init__(self, url):
self.cookiejar = requests.get(url).cookies
self.url = url
def check_domain(self, domain):
try:
base_domain = re.compile("(?<=\.).+\..+$").search(domain).group()
except AttributeError:
base_domain = domain
if base_domain in self.url:
print("\"prov=" + str(dict(self.cookiejar)["prov"]) + "\"")
else:
print("No cookies for " + domain + " in this jar!")
如果你这样做了:new_instance = getCookies("https://stackoverflow.com")
你可以这样做:new_instance.check_domain("meta.stackoverflow.com")
它将给出输出:"prov=5d4fda78-d042-2ee9-9a85-f507df184094"
当:new_instance.check_domain("google.com")
将输出:"No cookies for google.com in this jar!"
然后,如果您(如果需要)微调regex&create一个url列表,您可以首先遍历该列表以创建许多实例,并将它们保存在一个列表或dict中。在第二个循环中,您可以检查另一个url列表以查看它们的cookie是否可能存在于任何实例中。
旧答案
链接以解释的文档:items()
Dict-like items() that returns a list of name-value
tuples from the jar. Allows client-code to call
dict(RequestsCookieJar) and get a vanilla python dict of key value
pairs.
我想你要找的是:#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import requests
def getCookies(url):
r = requests.get(url)
print("\"prov=" + str(dict(r.cookies)["prov"]) + "\"")
现在我可以这样运行:>>> getCookies("https://stackoverflow.com")
"prov=f7712c78-b489-ee5f-5e8f-93c85ca06475"