Mô tả
Hướng dẫn sử dụng Selenium WebDriver với Python để thêm, lấy, xóa cookie cho một domain cụ thể.
Các phương thức chính
add_cookie(cookie_dict): Thêm cookie. Dict bắt buộc có 'name' và 'value'.get_cookies(): Lấy tất cả cookie (list of dicts).get_cookie(name): Lấy cookie theo tên.delete_all_cookies(): Xóa tất cả cookie.delete_cookie(name): Xóa cookie theo tên.
Yêu cầu quan trọng
Phải truy cập domain trước khi set cookie. Cookie gắn liền với domain, không thể set cho domain chưa load.
Ví dụ code hoàn chỉnh
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
# Khởi tạo driver (Chrome example)
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
try:
# 1. TRUY CẬP DOMAIN TRƯỚC
driver.get("https://www.tutorialspoint.com")
time.sleep(2) # Đợi load
# 2. THÊM COOKIE
cookie = {
'name': 'Automation',
'value': 'QA',
'domain': 'www.tutorialspoint.com', # Tùy chọn, mặc định domain hiện tại
'path': '/', # Tùy chọn
'secure': True, # Chỉ gửi qua HTTPS
'httpOnly': True, # Không truy cập qua JS
'expiry': int(time.time()) + 3600 # Hết hạn sau 1h
}
driver.add_cookie(cookie)
print("Đã thêm cookie:", driver.get_cookie('Automation'))
# 3. LẤY TẤT CẢ COOKIES
all_cookies = driver.get_cookies()
print(f"\nTổng số cookies: {len(all_cookies)}")
# 4. XÓA COOKIE CỤ THỂ
# driver.delete_cookie('Automation')
# 5. XÓA TẤT CẢ
driver.delete_all_cookies()
print(f"Số cookies sau xóa: {len(driver.get_cookies())}")
finally:
driver.quit()
Lưu ý quan trọng
- Domain cookie phải khớp với domain hiện tại hoặc domain cha (ví dụ: ở
sub.example.comcó thể set cookie cho.example.com). - Không thể set cookie cho domain khác hoàn toàn (ví dụ: ở google.com set cookie cho facebook.com).
expiryphải là Unix timestamp (giây từ epoch).- Cookie
secure=Truechỉ hoạt động trên HTTPS.
Kiểm tra cookie trong DevTools
F12 → Application → Cookies → chọn domain → xem cookie vừa thêm.