基本概念 Locator 基本概念
Playwright 有三个概念:browser、context、page;
browser 是通过在 BrowserType (chromium、firefox、webkit) 的 launch
方法打开的,可以传入 launchOptions,是否 headless 就是通过这个 launchOptions 控制;
context 是通过 browser 对象的 newContext
方法创建的,可以传入很多 options,包括 isMobile、viewport、userAgent 等,通过 Playwright.devices["iPhone 12"]
拿到的对象其大部分属性可作为 options 的属性(如下所示,除了 defaultBrowserType
),options 中没有 incognito 相关属性,因为 newContext 默认就创建隐私 context:
{
userAgent : 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1' ,
viewport : { width : 390 , height : 664 } ,
screen : { width : 390 , height : 844 } ,
deviceScaleFactor : 3 ,
isMobile : true ,
hasTouch : true ,
defaultBrowserType : 'webkit'
}
page 可以通过 browser 对象或 context 对象的 newPage
方法创建,如果通过 browser 的 newPage 方法创建,也可以接受很多 options,大概和 newContext 可接受的 options 一样,如果通过 context 的 newPage 方法创建,则不能传入 options,因为这时候创建的 page 会自动继承 context 的 options;
page 对象有很多方法,从页面提取信息基本上都在 page 的方法上实现,用的最多的可能是 page.goto
,注意不要用 page.$
或 page.$$
等返回值是 ElementHandle 的那些方法,因为官方建议使用 Locator ;
如果想发起 api 请求,可以创建一个 APIRequestContext,然后用 fetch、post、get 等方法发起请求,APIRequestContext 的创建有多种方法 ;
APIRequestContext.get()
等返回 APIResponse 对象,它有 body 等方法 ;
注意,APIRequestContext 是开发者自己发送的请求,如果是浏览器打开页面,由页面自动发送的请求,可以通过 page.on('request')
进行监测 ,对于 response,需要 page.on('response')
。
Locator
Locator 是 Playwright 的核心概念,可以通过 page.locator()
创建,它有很多方法 ;
page.locator()
接受一个 selector 参数,这个参数非常多变 ;
Locator 可以获取被选择的元素的很多信息,例如 context、attribute 等等,也可以对这个元素进行操作,例如 clidk、fill 等等;
await page.locator("text=新闻").getAttribute("href");
这行代码中,page.locator("text=新闻")
返回 Locator,getAttribute()
就是这个 Locator 的方法,返回被 select 的元素的 href 属性值;
注意,如果 page.locator()
返回了多个 Locator,即选中了多个元素,那 Locator 的某些方法无法被正常调用,例如 click 方法,因为通常我们不会同时 click 多个 Locator,Locator 的某些方法,例如 count、allTextContents 等方法可以使用,详情 。