Python Selenium Example Method for Operating Cookie

  • 2021-09-11 20:52:30
  • OfStack

With Selenium, you can also easily manipulate Cookies, such as obtaining, adding and deleting Cookies. The specific code is as follows:


from selenium import webdriver
browser = webdriver.Chrome()
browser.get('https://www.zhihu.com'
print(browser.get_cookies())
# browser.add_cookie({'aa':'aa','bb':'bb'})
# print(browser.get_cookies())
browser.delete_all_cookies()
print(browser.get_cookies())

It should be noted here that when adding cookie, the length should be the same as the length 1 of cookie you obtained. After deleting all cookie, the resulting cookie is empty.

Extension of basic knowledge points:

Properties of cookie

1 The attributes of cookie include:

Domain: Domain, which indicates under which domain or subdomain the current cookie belongs.

For Set-Cookie returned by the server, if the value of Domain is not specified, the value of Domain defaults to the primary domain name corresponding to the currently submitted request of http. For example, if you visit http://www. example. com and return an cookie without naming the value of domain, then its value is the default www. example. com.

Path: Represents the path to which cookie belongs. Expire time/Max-age: Indicates the expiry date of cookie. The value of expire is 1 time, after which the cookie becomes invalid. Or use max-age to specify how long after the current cookie expires. If one cookie returned by the server does not specify its expire time, it means that the validity period of this cookie is only the current session, that is, session cookie, and it expires after the current session session ends. Correspondingly, the cookie should be deleted by the browser when the page is closed. secure: Indicates that this cookie can only be transmitted using https. 1 is generally used for cookie containing authentication information. When it is required to transmit this cookie, it must be transmitted by https. httponly: Indicates that this cookie must be used for http or https transmissions. This means that browser scripts, such as in javascript, do not allow access to manipulate this cookie.

Related articles: