playwritght中with as的用法
最近在看playwritght 的源码,大家都知道运行playwright的基础代码如下:
with sync_playwright() as p: browser = p.chromium.launch(channel="chrome", headless=False) page = browser.new_page() page.goto("http://www.baidu.com") print(page.title()) browser.close()
关于python 中with as的用法详情大家可以参考文章:
以playwright脚本为例,详解Python with as处理异常的原理-CSDN博客
这里简单的说就是
with obj as f:
f.method(...)
# obj 表示一个对象(或是一个表达式, 结果为一个对象)
# 调用 obj 对象的 __enter__ 方法, 返回值赋值给 as 右边的变量 f,即: f = obj.__enter__()
# 执行 with 代码块中的代码 f.method(...)
# 执行完 with 代码块中的代码后, 无论是否发生异常, 调用 obj 的 __exit__ 方法,即: obj.__exit__(...)
with sync_playwright() as p 中的p的类型
那么在这里 with sync_playwright() as p ,p就是 sync_playwright() .__enter__()的返回值,我们来看一下源码:
def sync_playwright() -> PlaywrightContextManager: return PlaywrightContextManager()
继续跟踪PlaywrightContextManager源码如下:
class PlaywrightContextManager: def __init__(self) -> None: self._playwright: SyncPlaywright self._loop: asyncio.AbstractEventLoop self._own_loop = False self._watcher: Optional[asyncio.AbstractChildWatcher] = None def __enter__(self) -> SyncPlaywright: try: self._loop = asyncio.get_running_loop() except RuntimeError: self._loop = asyncio.new_event_loop() self._own_loop = True
发现函数__enter__(self) 的返回值是SyncPlaywright,关于->的用法可以参考文章
Python3.5 中->,即横杠和箭头,用来表示函数的返回值类型-CSDN博客
在ide中继续跟踪发现,点击SyncPlaywright,直接进入到类 class Playwright(SyncBase):
这是为什么呢?
回到PlaywrightContextManager源码处发现顶端引入代码如下:
from playwright.sync_api._generated import Playwright as SyncPlaywright
到这里真像大白!我们得知 with sync_playwright() as p 中的这个p 是类Playwright的实例。
验证p的类型
写一段代码来验证我的想法
with sync_playwright() as p: print(type(p)) #输出p的类型 ''' browser = p.chromium.launch(channel="chrome", headless=False) page = browser.new_page() page.goto("http://www.baidu.com") print(page.title()) browser.close() '''
输出:
<class 'playwright.sync_api._generated.Playwright'>
我的每一篇文章都希望帮助读者解决实际工作中遇到的问题!如果文章帮到了您,劳烦点赞、收藏、转发!您的鼓励是我不断更新文章最大的动力!