如何将 cookie 添加到 MechanicalSoup 中的现有 cookie
How to add a cookie to existing cookies in MechanicalSoup
我知道 MechanicalSoup 有一个名为 set_cookiejar() 的函数,但它完全取代了当前的 cookiejar。我想知道如何将新的 cookie 添加到现有的 cookie。
你可以这样实现
import mechanicalsoup
browser = mechanicalsoup.StatefulBrowser()
browser.open("your website")
cookie_obj = requests.cookies.create_cookie(name='cookie name', value='cookie value', domain='domain name')
browser.session.cookies.set_cookie(cookie_obj) # This will add your new cookie to existing cookies
另一种方法是
import mechanicalsoup
browser = mechanicalsoup.StatefulBrowser()
browser.open("your website")
new_cookie = {
"name":'COOKIE_NAME',
"value":'true',
"version":0,
"port":None,
# "port_specified":False,
"domain":'www.mydomain.com',
# "domain_specified":False,
# "domain_initial_dot":False,
"path":'/',
# "path_specified":True,
"secure":False,
"expires":None,
"discard":True,
"comment":None,
"comment_url":None,
"rest":{},
"rfc2109":False
}
browser.session.cookies.set(**new_cookie) # This will add your new cookie to existing cookies
来源:How to add a cookie to the cookiejar in python requests library
我知道 MechanicalSoup 有一个名为 set_cookiejar() 的函数,但它完全取代了当前的 cookiejar。我想知道如何将新的 cookie 添加到现有的 cookie。
你可以这样实现
import mechanicalsoup
browser = mechanicalsoup.StatefulBrowser()
browser.open("your website")
cookie_obj = requests.cookies.create_cookie(name='cookie name', value='cookie value', domain='domain name')
browser.session.cookies.set_cookie(cookie_obj) # This will add your new cookie to existing cookies
另一种方法是
import mechanicalsoup
browser = mechanicalsoup.StatefulBrowser()
browser.open("your website")
new_cookie = {
"name":'COOKIE_NAME',
"value":'true',
"version":0,
"port":None,
# "port_specified":False,
"domain":'www.mydomain.com',
# "domain_specified":False,
# "domain_initial_dot":False,
"path":'/',
# "path_specified":True,
"secure":False,
"expires":None,
"discard":True,
"comment":None,
"comment_url":None,
"rest":{},
"rfc2109":False
}
browser.session.cookies.set(**new_cookie) # This will add your new cookie to existing cookies
来源:How to add a cookie to the cookiejar in python requests library