How to use Selenium to handle cookies, I learned it thoroughly today!

01. Cookie introduction

HTTP protocol is a stateless protocol. Once the data exchange is completed, the connection between the client and the server is closed, and a new connection needs to be established to exchange data again, which means that the server cannot track the session from the connection. That is to say, even after connecting to the server for the first time and logging in successfully, the server still cannot know which user the current request is for the second time.

for example:

User A purchases an item and puts it in the shopping cart. When he purchases the item again, the server cannot determine whether the purchase belongs to user A’s session or user B’s session. To track this session, a mechanism must be introduced.

What is a session:

The process in which a user opens a browser to visit a website, browses any page on the website, and closes the browser after the visit is completed is called a session.

Picture

The emergence of cookies is to solve this problem. After logging in to the server for the first time, if the server needs to record the user status, it will use response to issue a cookie to the client browser, and the browser will store the cookie data. Save locally. When the user sends a second request, the cookie data stored in the last request will be automatically carried to the server. The server checks the name, value and other information stored in the cookie to identify the user status. The server can also use The content of the cookie needs to be modified.

A cookie is equivalent to the server issuing a pass to the clients, one for each person. No matter who visits, they must bring their own pass. This way the server can confirm the client’s identity from the pass. This is how cookies work.

The amount of data stored by cookies is limited. Different browsers have different storage sizes, but they generally do not exceed 4KB. Therefore, cookies can only store a small amount of data.

The emergence of cookies makes up for the stateless shortcomings of the HTTP protocol. However, cookies are stored on the client side and can be easily obtained through a browser or packet capture tool, so they are very unsafe.

02, session introduction

Session is another mechanism for recording client status. The difference is that cookies are saved in the client browser, while sessions are saved on the server. When the client browser accesses the server, the server records the client information on the server in some form. Data stored on the server will be more secure and less likely to be stolen. When the client browser visits again, it only needs to find the status of the customer from the session.

If the cookie mechanism determines the customer’s identity by checking the “passport” on the customer, then the session mechanism confirms the customer’s identity by checking the “customer details” on the server. Session is equivalent to a customer file created by the program on the server. When a customer comes to visit, he only needs to query the customer file table.

Storing sessions on the server also has certain disadvantages, that is, it will occupy server resources. However, now that the server has developed so far, it is more than enough to store some session information.

Illustration of how cookies and sessions work

Picture

The role of recording cookies

When a user logs in for the first time, he or she can check to log in directly next time or remember the password, which is achieved by using recording cookies.

The username and password (encrypted) information is recorded in the cookie. As long as the server receives the cookie when requesting, the recognition is successful, and the user is logged in by default.

Now I have also found a lot of test friends and created a communication group to share technology, sharing a lot of technical documents and video tutorials we collected.
If you don’t want to experience the feeling of not being able to find resources when studying on your own, having no one to answer your questions, and persisting for a few days before giving up.
You can join us to communicate. And there are many technical experts who have made certain achievements in automation, performance, security, test development, etc.
Share their experience, and also share many live lectures and technical salons
You can learn for free! Focus on it! Open source! ! !
QQ group number: 110685036

03. Selenium operation cookie

Method

Webdriver can read, add and delete cookie information.

The methods for webdriver to operate cookies are:

Picture

Example:

"""

1. Learning objectives:

    Master Selenium's cookie operations

2. Grammar

    2.1 Get all cookies

        driver.get.cookies()

        Returns the same list format dictionary type [{},{},{}]

    2.2 Add cookies

        driver.add_cookie(parameter)

        Parameters: dictionary format {"name":"name value","value":"value value"}

3.Demand

    Implement selenium's cookie operation

"""

# 1. Import selenium

from selenium import webdriver

from time import sleep



# 2. Open the browser

driver = webdriver.Chrome()



# 3. Open the registration A page

# Without opening a page, the cookie is [].

url = "http://www.baidu.com/"

driver.get(url)



# 4. Manipulate cookies

# 4.1 Get cookies

cookies = driver.get_cookies()

for cookies in cookies:

    # Value prints the name and value in the cookie

    print("%s -> %s" % (cookie['name'], cookie['value']))



print("=======================")

# 4.2 Get the specified attribute value of a cookie

#The parameter is the attribute value of name in a cookie

# Return None if not found

print(driver.get_cookie("BAIDUID"))



print("=======================")

# 4.3 Add cookies

cookie = {"name": "key-aaaaaaa", "value": "value-aaaaaaa"}

driver.add_cookie(cookie)



# Get again after adding

cookies = driver.get_cookies()

for cookies in cookies:

    print("%s -> %s" % (cookie['name'], cookie['value']))



print("=======================")

# 4.4 Delete specified cookies

#Delete based on name

driver.delete_cookie("key-aaaaaaa")

# Get again after deletion

cookies = driver.get_cookies()

for cookies in cookies:

    print("%s -> %s" % (cookie['name'], cookie['value']))



print("=======================")

# 4.5 Delete all cookies

driver.delete_all_cookies()

print(driver.get_cookies())



# 5. Close the browser

sleep(2)

driver.quit()

04. Cookie content parameter description

Picture

Description:

  • path:

    The valid range of the cookie is the valid range based on the domain parameter. If the path is set to “/”, it is valid in the entire domain.

  • secure:

    Whether the cookie only passes secure https, value 0 or 1. If the value is 1, the cookie is only valid on https connections. The default value is 0, which means the cookie is valid on both http and https connections. (0 or 1, can also represent False or True)

  • httpOnly:

    Cookie information cannot be read through js scripts, which can effectively prevent XSS attacks (cross-site scripting attacks), thus increasing the security of cookies. Even so, do not store important information in cookies.

Finally, I would like to thank everyone who has read my article carefully. Looking at the increase in fans and attention, there is always some courtesy. Although it is not a very valuable thing, if you can use it, you can take it directly!

Software testing interview document

We must study to find a high-paying job. The following interview questions are the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.