UI自动化系列之playwright CSS选择器

playwright-python中driver内置了一些选择器可供使用,源码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class PythonLocatorFactory {
generateLocator(base, kind, body, options = {}) {
switch (kind) {
case 'default':
if (options.hasText !== undefined) return `locator(${this.quote(body)}, has_text=${this.toHasText(options.hasText)})`;
if (options.hasNotText !== undefined) return `locator(${this.quote(body)}, has_not_text=${this.toHasText(options.hasNotText)})`;
return `locator(${this.quote(body)})`;
case 'frame':
return `frame_locator(${this.quote(body)})`;
case 'nth':
return `nth(${body})`;
case 'first':
return `first`;
case 'last':
return `last`;
case 'role':
const attrs = [];
if (isRegExp(options.name)) {
attrs.push(`name=${this.regexToString(options.name)}`);
} else if (typeof options.name === 'string') {
attrs.push(`name=${this.quote(options.name)}`);
if (options.exact) attrs.push(`exact=True`);
}
for (const {
name,
value
} of options.attrs) {
let valueString = typeof value === 'string' ? this.quote(value) : value;
if (typeof value === 'boolean') valueString = value ? 'True' : 'False';
attrs.push(`${(0, _stringUtils.toSnakeCase)(name)}=${valueString}`);
}
const attrString = attrs.length ? `, ${attrs.join(', ')}` : '';
return `get_by_role(${this.quote(body)}${attrString})`;
case 'has-text':
return `filter(has_text=${this.toHasText(body)})`;
case 'has-not-text':
return `filter(has_not_text=${this.toHasText(body)})`;
case 'has':
return `filter(has=${body})`;
case 'hasNot':
return `filter(has_not=${body})`;
case 'and':
return `and_(${body})`;
case 'or':
return `or_(${body})`;
case 'chain':
return `locator(${body})`;
case 'test-id':
return `get_by_test_id(${this.toTestIdValue(body)})`;
case 'text':
return this.toCallWithExact('get_by_text', body, !!options.exact);
case 'alt':
return this.toCallWithExact('get_by_alt_text', body, !!options.exact);
case 'placeholder':
return this.toCallWithExact('get_by_placeholder', body, !!options.exact);
case 'label':
return this.toCallWithExact('get_by_label', body, !!options.exact);
case 'title':
return this.toCallWithExact('get_by_title', body, !!options.exact);
default:
throw new Error('Unknown selector kind ' + kind);
}
}

example: https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_Selectors

1
2
3
4
5
6
7
8
//div元素下有快捷中心字样
page.wait_for_selector("div:has-text('快捷中心')")

//任意元素下有快捷中心字样
page.wait_for_selector("div:has-text('快捷中心')")




本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!