or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-features.mdapi-testing.mdassertions.mdbrowser-management.mdelement-location.mdindex.mdmobile-testing.mdnetwork-interception.mdpage-interaction.md

page-interaction.mddocs/

0

# Page Interaction

1

2

Comprehensive page navigation, content manipulation, and interaction capabilities for automating web applications. Includes navigation methods, JavaScript execution, form handling, and advanced page state management.

3

4

## Capabilities

5

6

### Page Navigation

7

8

Navigate between pages, handle redirects, and manage page loading states.

9

10

```python { .api }

11

class Page:

12

url: str

13

main_frame: Frame

14

frames: List[Frame]

15

context: BrowserContext

16

17

def goto(

18

self,

19

url: str,

20

timeout: Optional[float] = None,

21

wait_until: Optional[str] = None,

22

referer: Optional[str] = None

23

) -> Optional[Response]:

24

"""

25

Navigate to URL.

26

27

Args:

28

url: Target URL

29

timeout: Navigation timeout in milliseconds

30

wait_until: When to consider navigation complete

31

('load', 'domcontentloaded', 'networkidle', 'commit')

32

referer: Referer header value

33

34

Returns:

35

Optional[Response]: Main resource response (None for data URLs)

36

"""

37

38

def go_back(

39

self,

40

timeout: Optional[float] = None,

41

wait_until: Optional[str] = None

42

) -> Optional[Response]:

43

"""

44

Navigate back in browser history.

45

46

Args:

47

timeout: Navigation timeout in milliseconds

48

wait_until: Load completion criteria

49

50

Returns:

51

Optional[Response]: Response if navigation occurred

52

"""

53

54

def go_forward(

55

self,

56

timeout: Optional[float] = None,

57

wait_until: Optional[str] = None

58

) -> Optional[Response]:

59

"""

60

Navigate forward in browser history.

61

62

Args:

63

timeout: Navigation timeout in milliseconds

64

wait_until: Load completion criteria

65

66

Returns:

67

Optional[Response]: Response if navigation occurred

68

"""

69

70

def reload(

71

self,

72

timeout: Optional[float] = None,

73

wait_until: Optional[str] = None

74

) -> Optional[Response]:

75

"""

76

Reload current page.

77

78

Args:

79

timeout: Navigation timeout in milliseconds

80

wait_until: Load completion criteria

81

82

Returns:

83

Optional[Response]: Main resource response

84

"""

85

86

def wait_for_load_state(

87

self,

88

state: Optional[str] = None,

89

timeout: Optional[float] = None

90

) -> None:

91

"""

92

Wait for page to reach specified load state.

93

94

Args:

95

state: Load state ('load', 'domcontentloaded', 'networkidle')

96

timeout: Wait timeout in milliseconds

97

"""

98

99

def wait_for_url(

100

self,

101

url: Union[str, Pattern, Callable[[str], bool]],

102

timeout: Optional[float] = None,

103

wait_until: Optional[str] = None

104

) -> None:

105

"""

106

Wait for page URL to match pattern.

107

108

Args:

109

url: URL pattern to match

110

timeout: Wait timeout in milliseconds

111

wait_until: Load completion criteria

112

"""

113

```

114

115

### Content Access and Manipulation

116

117

Get and set page content, execute JavaScript, and manipulate page state.

118

119

```python { .api }

120

class Page:

121

def content(self) -> str:

122

"""

123

Get HTML content of the page.

124

125

Returns:

126

str: Full HTML content

127

"""

128

129

def set_content(

130

self,

131

html: str,

132

timeout: Optional[float] = None,

133

wait_until: Optional[str] = None

134

) -> None:

135

"""

136

Set HTML content of the page.

137

138

Args:

139

html: HTML content to set

140

timeout: Load timeout in milliseconds

141

wait_until: Load completion criteria

142

"""

143

144

def title(self) -> str:

145

"""

146

Get page title.

147

148

Returns:

149

str: Page title

150

"""

151

152

def evaluate(

153

self,

154

expression: str,

155

arg: Any = None

156

) -> Any:

157

"""

158

Execute JavaScript expression in page context.

159

160

Args:

161

expression: JavaScript expression to evaluate

162

arg: Argument to pass to expression

163

164

Returns:

165

Any: Expression result (serializable values only)

166

"""

167

168

def evaluate_handle(

169

self,

170

expression: str,

171

arg: Any = None

172

) -> JSHandle:

173

"""

174

Execute JavaScript and return object handle.

175

176

Args:

177

expression: JavaScript expression to evaluate

178

arg: Argument to pass to expression

179

180

Returns:

181

JSHandle: Handle to JavaScript object

182

"""

183

184

def add_script_tag(

185

self,

186

url: Optional[str] = None,

187

path: Optional[str] = None,

188

content: Optional[str] = None,

189

type: Optional[str] = None

190

) -> ElementHandle:

191

"""

192

Add script tag to page.

193

194

Args:

195

url: Script URL

196

path: Path to script file

197

content: Script content

198

type: Script type attribute

199

200

Returns:

201

ElementHandle: Script element handle

202

"""

203

204

def add_style_tag(

205

self,

206

url: Optional[str] = None,

207

path: Optional[str] = None,

208

content: Optional[str] = None

209

) -> ElementHandle:

210

"""

211

Add style tag to page.

212

213

Args:

214

url: Stylesheet URL

215

path: Path to stylesheet file

216

content: CSS content

217

218

Returns:

219

ElementHandle: Style element handle

220

"""

221

```

222

223

### Element Interaction (Legacy API)

224

225

Direct element interaction methods using CSS selectors. Note: Modern applications should prefer the Locator API.

226

227

```python { .api }

228

class Page:

229

def click(

230

self,

231

selector: str,

232

modifiers: Optional[List[str]] = None,

233

position: Optional[Position] = None,

234

delay: Optional[float] = None,

235

button: Optional[str] = None,

236

click_count: Optional[int] = None,

237

timeout: Optional[float] = None,

238

force: Optional[bool] = None,

239

no_wait_after: Optional[bool] = None,

240

trial: Optional[bool] = None,

241

strict: Optional[bool] = None

242

) -> None:

243

"""

244

Click element matching selector.

245

246

Args:

247

selector: Element selector

248

modifiers: Modifier keys ('Alt', 'Control', 'Meta', 'Shift')

249

position: Click position relative to element

250

delay: Delay between mousedown and mouseup

251

button: Mouse button ('left', 'right', 'middle')

252

click_count: Number of clicks (1 for single, 2 for double)

253

timeout: Action timeout in milliseconds

254

force: Skip actionability checks

255

no_wait_after: Don't wait for navigation

256

trial: Perform all checks without action

257

strict: Throw on multiple matches

258

"""

259

260

def dblclick(

261

self,

262

selector: str,

263

modifiers: Optional[List[str]] = None,

264

position: Optional[Position] = None,

265

delay: Optional[float] = None,

266

button: Optional[str] = None,

267

timeout: Optional[float] = None,

268

force: Optional[bool] = None,

269

no_wait_after: Optional[bool] = None,

270

trial: Optional[bool] = None,

271

strict: Optional[bool] = None

272

) -> None:

273

"""

274

Double-click element matching selector.

275

276

Args:

277

selector: Element selector

278

modifiers: Modifier keys

279

position: Click position

280

delay: Delay between clicks

281

button: Mouse button

282

timeout: Action timeout in milliseconds

283

force: Skip actionability checks

284

no_wait_after: Don't wait for navigation

285

trial: Perform checks without action

286

strict: Throw on multiple matches

287

"""

288

289

def fill(

290

self,

291

selector: str,

292

value: str,

293

timeout: Optional[float] = None,

294

no_wait_after: Optional[bool] = None,

295

force: Optional[bool] = None,

296

strict: Optional[bool] = None

297

) -> None:

298

"""

299

Fill input field with value.

300

301

Args:

302

selector: Input element selector

303

value: Value to fill

304

timeout: Action timeout in milliseconds

305

no_wait_after: Don't wait for navigation

306

force: Skip actionability checks

307

strict: Throw on multiple matches

308

"""

309

310

def type(

311

self,

312

selector: str,

313

text: str,

314

delay: Optional[float] = None,

315

timeout: Optional[float] = None,

316

no_wait_after: Optional[bool] = None,

317

strict: Optional[bool] = None

318

) -> None:

319

"""

320

Type text into element character by character.

321

322

Args:

323

selector: Element selector

324

text: Text to type

325

delay: Delay between keystrokes in milliseconds

326

timeout: Action timeout in milliseconds

327

no_wait_after: Don't wait for navigation

328

strict: Throw on multiple matches

329

"""

330

331

def press(

332

self,

333

selector: str,

334

key: str,

335

delay: Optional[float] = None,

336

timeout: Optional[float] = None,

337

no_wait_after: Optional[bool] = None,

338

strict: Optional[bool] = None

339

) -> None:

340

"""

341

Press key on element.

342

343

Args:

344

selector: Element selector

345

key: Key to press ('Enter', 'Escape', 'Tab', etc.)

346

delay: Delay between keydown and keyup

347

timeout: Action timeout in milliseconds

348

no_wait_after: Don't wait for navigation

349

strict: Throw on multiple matches

350

"""

351

352

def check(

353

self,

354

selector: str,

355

timeout: Optional[float] = None,

356

force: Optional[bool] = None,

357

no_wait_after: Optional[bool] = None,

358

trial: Optional[bool] = None,

359

strict: Optional[bool] = None

360

) -> None:

361

"""

362

Check checkbox or radio button.

363

364

Args:

365

selector: Element selector

366

timeout: Action timeout in milliseconds

367

force: Skip actionability checks

368

no_wait_after: Don't wait for navigation

369

trial: Perform checks without action

370

strict: Throw on multiple matches

371

"""

372

373

def uncheck(

374

self,

375

selector: str,

376

timeout: Optional[float] = None,

377

force: Optional[bool] = None,

378

no_wait_after: Optional[bool] = None,

379

trial: Optional[bool] = None,

380

strict: Optional[bool] = None

381

) -> None:

382

"""

383

Uncheck checkbox.

384

385

Args:

386

selector: Element selector

387

timeout: Action timeout in milliseconds

388

force: Skip actionability checks

389

no_wait_after: Don't wait for navigation

390

trial: Perform checks without action

391

strict: Throw on multiple matches

392

"""

393

394

def select_option(

395

self,

396

selector: str,

397

value: Union[str, List[str], None] = None,

398

index: Union[int, List[int], None] = None,

399

label: Union[str, List[str], None] = None,

400

element: Union[ElementHandle, List[ElementHandle], None] = None,

401

timeout: Optional[float] = None,

402

force: Optional[bool] = None,

403

no_wait_after: Optional[bool] = None,

404

strict: Optional[bool] = None

405

) -> List[str]:

406

"""

407

Select option(s) in select element.

408

409

Args:

410

selector: Select element selector

411

value: Option value(s) to select

412

index: Option index(es) to select

413

label: Option label(s) to select

414

element: Option element(s) to select

415

timeout: Action timeout in milliseconds

416

force: Skip actionability checks

417

no_wait_after: Don't wait for navigation

418

strict: Throw on multiple matches

419

420

Returns:

421

List[str]: Selected option values

422

"""

423

424

def set_input_files(

425

self,

426

selector: str,

427

files: Union[str, List[str], FilePayload, List[FilePayload]],

428

timeout: Optional[float] = None,

429

no_wait_after: Optional[bool] = None,

430

strict: Optional[bool] = None

431

) -> None:

432

"""

433

Set files for file input element.

434

435

Args:

436

selector: File input selector

437

files: File path(s) or file payload(s)

438

timeout: Action timeout in milliseconds

439

no_wait_after: Don't wait for navigation

440

strict: Throw on multiple matches

441

"""

442

443

def hover(

444

self,

445

selector: str,

446

modifiers: Optional[List[str]] = None,

447

position: Optional[Position] = None,

448

timeout: Optional[float] = None,

449

force: Optional[bool] = None,

450

trial: Optional[bool] = None,

451

strict: Optional[bool] = None

452

) -> None:

453

"""

454

Hover over element.

455

456

Args:

457

selector: Element selector

458

modifiers: Modifier keys

459

position: Hover position

460

timeout: Action timeout in milliseconds

461

force: Skip actionability checks

462

trial: Perform checks without action

463

strict: Throw on multiple matches

464

"""

465

466

def focus(

467

self,

468

selector: str,

469

timeout: Optional[float] = None,

470

strict: Optional[bool] = None

471

) -> None:

472

"""

473

Focus element.

474

475

Args:

476

selector: Element selector

477

timeout: Action timeout in milliseconds

478

strict: Throw on multiple matches

479

"""

480

481

def drag_and_drop(

482

self,

483

source: str,

484

target: str,

485

force: Optional[bool] = None,

486

no_wait_after: Optional[bool] = None,

487

timeout: Optional[float] = None,

488

trial: Optional[bool] = None,

489

strict: Optional[bool] = None,

490

source_position: Optional[Position] = None,

491

target_position: Optional[Position] = None

492

) -> None:

493

"""

494

Drag element from source to target.

495

496

Args:

497

source: Source element selector

498

target: Target element selector

499

force: Skip actionability checks

500

no_wait_after: Don't wait for navigation

501

timeout: Action timeout in milliseconds

502

trial: Perform checks without action

503

strict: Throw on multiple matches

504

source_position: Drag start position

505

target_position: Drop position

506

"""

507

```

508

509

### Element State Queries

510

511

Check element states using CSS selectors.

512

513

```python { .api }

514

class Page:

515

def is_checked(

516

self,

517

selector: str,

518

timeout: Optional[float] = None,

519

strict: Optional[bool] = None

520

) -> bool:

521

"""

522

Check if element is checked.

523

524

Args:

525

selector: Element selector

526

timeout: Query timeout in milliseconds

527

strict: Throw on multiple matches

528

529

Returns:

530

bool: True if checked

531

"""

532

533

def is_disabled(

534

self,

535

selector: str,

536

timeout: Optional[float] = None,

537

strict: Optional[bool] = None

538

) -> bool:

539

"""

540

Check if element is disabled.

541

542

Args:

543

selector: Element selector

544

timeout: Query timeout in milliseconds

545

strict: Throw on multiple matches

546

547

Returns:

548

bool: True if disabled

549

"""

550

551

def is_editable(

552

self,

553

selector: str,

554

timeout: Optional[float] = None,

555

strict: Optional[bool] = None

556

) -> bool:

557

"""

558

Check if element is editable.

559

560

Args:

561

selector: Element selector

562

timeout: Query timeout in milliseconds

563

strict: Throw on multiple matches

564

565

Returns:

566

bool: True if editable

567

"""

568

569

def is_enabled(

570

self,

571

selector: str,

572

timeout: Optional[float] = None,

573

strict: Optional[bool] = None

574

) -> bool:

575

"""

576

Check if element is enabled.

577

578

Args:

579

selector: Element selector

580

timeout: Query timeout in milliseconds

581

strict: Throw on multiple matches

582

583

Returns:

584

bool: True if enabled

585

"""

586

587

def is_hidden(

588

self,

589

selector: str,

590

timeout: Optional[float] = None,

591

strict: Optional[bool] = None

592

) -> bool:

593

"""

594

Check if element is hidden.

595

596

Args:

597

selector: Element selector

598

timeout: Query timeout in milliseconds

599

strict: Throw on multiple matches

600

601

Returns:

602

bool: True if hidden

603

"""

604

605

def is_visible(

606

self,

607

selector: str,

608

timeout: Optional[float] = None,

609

strict: Optional[bool] = None

610

) -> bool:

611

"""

612

Check if element is visible.

613

614

Args:

615

selector: Element selector

616

timeout: Query timeout in milliseconds

617

strict: Throw on multiple matches

618

619

Returns:

620

bool: True if visible

621

"""

622

```

623

624

### Waiting and Synchronization

625

626

Wait for various page conditions and events.

627

628

```python { .api }

629

class Page:

630

def wait_for_selector(

631

self,

632

selector: str,

633

timeout: Optional[float] = None,

634

state: Optional[str] = None,

635

strict: Optional[bool] = None

636

) -> Optional[ElementHandle]:

637

"""

638

Wait for element matching selector.

639

640

Args:

641

selector: Element selector

642

timeout: Wait timeout in milliseconds

643

state: Element state ('attached', 'detached', 'visible', 'hidden')

644

strict: Throw on multiple matches

645

646

Returns:

647

Optional[ElementHandle]: Element handle (None if detached)

648

"""

649

650

def wait_for_function(

651

self,

652

expression: str,

653

arg: Any = None,

654

timeout: Optional[float] = None,

655

polling: Union[float, str, None] = None

656

) -> JSHandle:

657

"""

658

Wait for JavaScript function to return truthy value.

659

660

Args:

661

expression: JavaScript function to evaluate

662

arg: Argument to pass to function

663

timeout: Wait timeout in milliseconds

664

polling: Polling interval ('raf' or milliseconds)

665

666

Returns:

667

JSHandle: Function result handle

668

"""

669

670

def wait_for_timeout(self, timeout: float) -> None:

671

"""

672

Wait for specified time.

673

674

Args:

675

timeout: Wait time in milliseconds

676

"""

677

678

def wait_for_event(

679

self,

680

event: str,

681

predicate: Optional[Callable] = None,

682

timeout: Optional[float] = None

683

) -> Any:

684

"""

685

Wait for page event.

686

687

Args:

688

event: Event name ('dialog', 'download', 'filechooser', etc.)

689

predicate: Event filter function

690

timeout: Wait timeout in milliseconds

691

692

Returns:

693

Any: Event data

694

"""

695

696

def expect_event(

697

self,

698

event: str,

699

predicate: Optional[Callable] = None,

700

timeout: Optional[float] = None

701

) -> EventContextManager:

702

"""

703

Expect page event with context manager.

704

705

Args:

706

event: Event name

707

predicate: Event filter function

708

timeout: Wait timeout in milliseconds

709

710

Returns:

711

EventContextManager: Event context manager

712

"""

713

```

714

715

### Media and Screenshots

716

717

Capture page content as images or PDFs.

718

719

```python { .api }

720

class Page:

721

def screenshot(

722

self,

723

timeout: Optional[float] = None,

724

type: Optional[str] = None,

725

path: Optional[str] = None,

726

quality: Optional[int] = None,

727

omit_background: Optional[bool] = None,

728

full_page: Optional[bool] = None,

729

clip: Optional[FloatRect] = None,

730

animations: Optional[str] = None,

731

caret: Optional[str] = None,

732

scale: Optional[str] = None,

733

mask: Optional[List[Locator]] = None

734

) -> bytes:

735

"""

736

Take page screenshot.

737

738

Args:

739

timeout: Screenshot timeout in milliseconds

740

type: Image type ('png', 'jpeg')

741

path: File path to save screenshot

742

quality: JPEG quality (0-100)

743

omit_background: Hide default background

744

full_page: Capture full scrollable page

745

clip: Capture specific area

746

animations: Handle animations ('disabled', 'allow')

747

caret: Handle text caret ('hide', 'initial')

748

scale: Viewport scale ('css', 'device')

749

mask: Elements to mask in screenshot

750

751

Returns:

752

bytes: Screenshot data

753

"""

754

755

def pdf(

756

self,

757

scale: Optional[float] = None,

758

display_header_footer: Optional[bool] = None,

759

header_template: Optional[str] = None,

760

footer_template: Optional[str] = None,

761

print_background: Optional[bool] = None,

762

landscape: Optional[bool] = None,

763

page_ranges: Optional[str] = None,

764

format: Optional[str] = None,

765

width: Optional[str] = None,

766

height: Optional[str] = None,

767

margin: Optional[PdfMargins] = None,

768

path: Optional[str] = None,

769

prefer_css_page_size: Optional[bool] = None,

770

tagged: Optional[bool] = None,

771

outline: Optional[bool] = None

772

) -> bytes:

773

"""

774

Generate PDF of page.

775

776

Args:

777

scale: Scale factor (0.1-2)

778

display_header_footer: Show header/footer

779

header_template: HTML template for header

780

footer_template: HTML template for footer

781

print_background: Include background graphics

782

landscape: Landscape orientation

783

page_ranges: Page ranges to print

784

format: Paper format ('A4', 'Letter', etc.)

785

width: Paper width

786

height: Paper height

787

margin: Page margins

788

path: File path to save PDF

789

prefer_css_page_size: Use CSS page size

790

tagged: Generate tagged PDF

791

outline: Generate PDF outline

792

793

Returns:

794

bytes: PDF data

795

"""

796

```

797

798

### Input Devices

799

800

Direct access to keyboard, mouse, and touch input.

801

802

```python { .api }

803

class Page:

804

keyboard: Keyboard

805

mouse: Mouse

806

touchscreen: Touchscreen

807

808

class Keyboard:

809

def down(self, key: str) -> None:

810

"""Press key down."""

811

812

def up(self, key: str) -> None:

813

"""Release key."""

814

815

def press(

816

self,

817

key: str,

818

delay: Optional[float] = None

819

) -> None:

820

"""Press and release key."""

821

822

def insert_text(self, text: str) -> None:

823

"""Insert text without key events."""

824

825

def type(

826

self,

827

text: str,

828

delay: Optional[float] = None

829

) -> None:

830

"""Type text with key events."""

831

832

class Mouse:

833

def move(

834

self,

835

x: float,

836

y: float,

837

steps: Optional[int] = None

838

) -> None:

839

"""Move mouse to coordinates."""

840

841

def down(

842

self,

843

button: Optional[str] = None,

844

click_count: Optional[int] = None

845

) -> None:

846

"""Press mouse button."""

847

848

def up(

849

self,

850

button: Optional[str] = None,

851

click_count: Optional[int] = None

852

) -> None:

853

"""Release mouse button."""

854

855

def click(

856

self,

857

x: float,

858

y: float,

859

delay: Optional[float] = None,

860

button: Optional[str] = None,

861

click_count: Optional[int] = None

862

) -> None:

863

"""Click at coordinates."""

864

865

def dblclick(

866

self,

867

x: float,

868

y: float,

869

delay: Optional[float] = None,

870

button: Optional[str] = None

871

) -> None:

872

"""Double-click at coordinates."""

873

874

def wheel(self, delta_x: float, delta_y: float) -> None:

875

"""Scroll mouse wheel."""

876

877

class Touchscreen:

878

def tap(self, x: float, y: float) -> None:

879

"""Tap at coordinates."""

880

```

881

882

## Usage Examples

883

884

### Basic Page Navigation

885

886

```python

887

from playwright.sync_api import sync_playwright

888

889

with sync_playwright() as p:

890

browser = p.chromium.launch()

891

page = browser.new_page()

892

893

# Navigate and wait for load

894

response = page.goto("https://example.com")

895

print(f"Status: {response.status}")

896

897

# Navigate with specific wait condition

898

page.goto("https://spa-app.com", wait_until="networkidle")

899

900

# Browser navigation

901

page.go_back()

902

page.go_forward()

903

page.reload()

904

905

browser.close()

906

```

907

908

### Form Interaction

909

910

```python

911

with sync_playwright() as p:

912

browser = p.chromium.launch()

913

page = browser.new_page()

914

915

page.goto("https://example.com/form")

916

917

# Fill form fields

918

page.fill("#name", "John Doe")

919

page.fill("#email", "john@example.com")

920

page.type("#message", "Hello world!", delay=100)

921

922

# Select options

923

page.select_option("#country", "US")

924

page.check("#subscribe")

925

926

# Submit form

927

page.click("button[type=submit]")

928

page.wait_for_load_state("networkidle")

929

930

browser.close()

931

```

932

933

### JavaScript Execution

934

935

```python

936

with sync_playwright() as p:

937

browser = p.chromium.launch()

938

page = browser.new_page()

939

940

page.goto("https://example.com")

941

942

# Execute JavaScript

943

title = page.evaluate("document.title")

944

print(f"Title: {title}")

945

946

# Pass arguments

947

result = page.evaluate("(x, y) => x + y", {"x": 5, "y": 3})

948

print(f"Result: {result}")

949

950

# Get object handle

951

window_handle = page.evaluate_handle("window")

952

print(f"Window: {window_handle}")

953

954

browser.close()

955

```

956

957

### Advanced Waiting

958

959

```python

960

with sync_playwright() as p:

961

browser = p.chromium.launch()

962

page = browser.new_page()

963

964

page.goto("https://dynamic-app.com")

965

966

# Wait for element

967

page.wait_for_selector(".loading", state="detached")

968

element = page.wait_for_selector(".results")

969

970

# Wait for function

971

page.wait_for_function("window.dataLoaded === true")

972

973

# Wait for event

974

with page.expect_event("dialog") as dialog_info:

975

page.click("#show-alert")

976

dialog = dialog_info.value

977

dialog.accept()

978

979

browser.close()

980

```

981

982

### Screenshot and PDF

983

984

```python

985

with sync_playwright() as p:

986

browser = p.chromium.launch()

987

page = browser.new_page()

988

989

page.goto("https://example.com")

990

991

# Full page screenshot

992

page.screenshot(path="page.png", full_page=True)

993

994

# Specific element area

995

page.screenshot(

996

path="header.png",

997

clip={"x": 0, "y": 0, "width": 800, "height": 100}

998

)

999

1000

# Generate PDF

1001

page.pdf(

1002

path="page.pdf",

1003

format="A4",

1004

margin={"top": "1in", "bottom": "1in"}

1005

)

1006

1007

browser.close()

1008

```

1009

1010

### Dialog Handling

1011

1012

Handle browser dialog boxes including alerts, confirmations, and prompts.

1013

1014

```python { .api }

1015

class Dialog:

1016

"""Browser dialog (alert, confirm, prompt) handler."""

1017

1018

@property

1019

def type(self) -> str:

1020

"""Dialog type: 'alert', 'beforeunload', 'confirm', or 'prompt'."""

1021

1022

@property

1023

def message(self) -> str:

1024

"""Message displayed in the dialog."""

1025

1026

@property

1027

def default_value(self) -> str:

1028

"""Default value for prompt dialogs."""

1029

1030

def accept(self, prompt_text: Optional[str] = None) -> None:

1031

"""Accept the dialog, optionally providing text for prompts."""

1032

1033

def dismiss(self) -> None:

1034

"""Dismiss the dialog."""

1035

```

1036

1037

### File Upload

1038

1039

Handle file upload dialogs and file selection.

1040

1041

```python { .api }

1042

class FileChooser:

1043

"""File upload dialog handler."""

1044

1045

@property

1046

def page(self) -> Page:

1047

"""Page that opened the file chooser."""

1048

1049

@property

1050

def element(self) -> ElementHandle:

1051

"""Element that triggered the file chooser."""

1052

1053

@property

1054

def is_multiple(self) -> bool:

1055

"""Whether multiple files can be selected."""

1056

1057

def set_files(

1058

self,

1059

files: Union[str, pathlib.Path, List[Union[str, pathlib.Path]]],

1060

timeout: Optional[float] = None

1061

) -> None:

1062

"""Set files for upload."""

1063

```

1064

1065

### Download Handling

1066

1067

Manage file downloads triggered by user actions.

1068

1069

```python { .api }

1070

class Download:

1071

"""File download handler."""

1072

1073

@property

1074

def page(self) -> Page:

1075

"""Page that initiated the download."""

1076

1077

@property

1078

def url(self) -> str:

1079

"""Download URL."""

1080

1081

@property

1082

def suggested_filename(self) -> str:

1083

"""Browser-suggested filename."""

1084

1085

def path(self) -> Optional[pathlib.Path]:

1086

"""Download file path (None for cancelled downloads)."""

1087

1088

def save_as(self, path: Union[str, pathlib.Path]) -> None:

1089

"""Save download to specific path."""

1090

1091

def delete(self) -> None:

1092

"""Delete downloaded file."""

1093

1094

def cancel(self) -> None:

1095

"""Cancel the download."""

1096

1097

def failure(self) -> Optional[str]:

1098

"""Download failure reason if failed."""

1099

```

1100

1101

### JavaScript Object Handling

1102

1103

Handle JavaScript objects and values from page evaluation.

1104

1105

```python { .api }

1106

class JSHandle:

1107

"""Handle to JavaScript object in page context."""

1108

1109

def evaluate(

1110

self,

1111

expression: str,

1112

arg: Any = None

1113

) -> Any:

1114

"""Evaluate JavaScript with this handle as context."""

1115

1116

def evaluate_handle(

1117

self,

1118

expression: str,

1119

arg: Any = None

1120

) -> JSHandle:

1121

"""Evaluate JavaScript and return handle to result."""

1122

1123

def get_property(self, property_name: str) -> JSHandle:

1124

"""Get handle to object property."""

1125

1126

def get_properties(self) -> Dict[str, JSHandle]:

1127

"""Get all object properties as handles."""

1128

1129

def as_element(self) -> Optional[ElementHandle]:

1130

"""Convert to ElementHandle if this is a DOM element."""

1131

1132

def dispose(self) -> None:

1133

"""Dispose the handle and release memory."""

1134

1135

def json_value(self) -> Any:

1136

"""JSON representation of the object."""

1137

```

1138

1139

Usage examples:

1140

1141

```python

1142

# Dialog handling

1143

def handle_alert(dialog):

1144

print(f"Alert: {dialog.message}")

1145

dialog.accept()

1146

1147

page.on("dialog", handle_alert)

1148

page.click("button[onclick='alert()']")

1149

1150

# File upload

1151

with page.expect_file_chooser() as fc_info:

1152

page.click("input[type=file]")

1153

file_chooser = fc_info.value

1154

file_chooser.set_files("document.pdf")

1155

1156

# Download handling

1157

with page.expect_download() as download_info:

1158

page.click("a[download]")

1159

download = download_info.value

1160

download.save_as("./downloads/file.pdf")

1161

```