python requests cookies怎么转为_如何将requests.RequestsCookieJar转换为字符串

新答案

好吧,所以我还是不知道你到底想达到什么目的。

如果您想从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"

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值