[playwright] Cookie vs Storage 登录

124次阅读
没有评论

cookie

playwright 支持cookie认证的方法是add_cookies, 跟进下源码,看下该方法的使用方式

Parameters
----------
cookies : List[
{
name: str,
value: str,
url: Union[str, NoneType],
domain: Union[str, NoneType],
path: Union[str, NoneType],
expires: Union[float, NoneType],
httpOnly: Union[bool, NoneType],
secure: Union[bool, NoneType],
sameSite: Union["Lax", "None", "Strict", NoneType]
}
]

格式很眼熟,建议使用chrome 插件EditThisCookie导出cookie

注意

这里大小写有问题,目前遇到的坑是true、false、lax开头字母应是大写

'''
from playwright.sync_api import sync_playwright

url = "http://blog.1314mylove.com"

def run(playwright):
    chromium = playwright.chromium
    browser = chromium.launch(headless=False)
    context = browser.new_context()
    true = True
    false = False
    cookie_data =[
{
    "domain": "blog.1314mylove.com",
    "hostOnly": true,
    "httpOnly": true,
    "name": "JSESSIONID",
    "path": "/",
    "sameSite": "Lax",
    "secure": false,
    "session": true,
    "storeId": "0",
    "value": "9f66bb77-3efd-4256-b036-88434fea17eb1",
    "id": 1
},
{
    "domain": "blog.1314mylove.com",
    "expirationDate": 3345090212.14289,
    "hostOnly": true,
    "httpOnly": true,
    "name": "rememberMe",
    "path": "/",
    "sameSite": "Lax",
    "secure": false,
    "session": false,
    "storeId": "0",
    "value": "ApioONLWuo",
    "id": 2
}
]
    context.add_cookies(cookie_data)
    page = context.new_page()
    page.goto(url)
    page.wait_for_timeout(1000)
    browser.close()

with sync_playwright() as playwright:
    run(playwright)

storage

playwright 支持自动保存storage

  • 保存storage
python -m playwright cr https://blog.1314mylove.com --save-storage storage_file
  • 加载storage
python -m playwright cr https://blog.1314mylove.com --load-storage storage_file

python代码调用的方式是storage_state

from playwright.sync_api import sync_playwright

url = "http://blog.1314mylove.com"

def run(playwright):
    chromium = playwright.chromium
    browser = chromium.launch(headless=False)
    with open(storage_file) as f:
        storage_state = json.loads(f.read())
    context = browser.new_context(storage_state=storage_state)
    page = context.new_page()
    page.goto(url)
    page.wait_for_timeout(1000)
    browser.close()

with sync_playwright() as playwright:
    run(playwright)

小草稿
版权声明:本站原创文章,由小草稿2021-03-31发表,共计1849字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)