同一个程序开启多个浏览器
from playwright.sync_api import sync_playwright# 全局变量(要注意,是整个环境全局变量,后续所有涉及playwright的浏览器创建都要基于改变量创建)playwright = sync_playwright().start()def get_context():browser = playwright.chromium.launch(executable_path="/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",headless=False,args=["--disable-blink-features=AutomationControlled"],)context = browser.new_context(bypass_csp=True,viewport={"width": 1920, "height": 1080},)return contextif __name__ == '__main__':c1 = get_context()c2 = get_context()p1 = c1.new_page()p1.goto('https://baidu.com')print(p1.title())p2 = c2.new_page()p2.goto('https://baidu.com')print(p2.title())c1.browser.close()c2.browser.close()
Django ORM 与 Playwright 一起使用
在没有经过设置的情况下,在django项目中使用playwright后,调用django orm会出现如下报错。django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
解决的办法是在setting.py文件中,设置DJANGO_ALLOW_ASYNC_UNSAFE参数
# 在setting.py文件中加入,即可解决import osos.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
