---
# System prepended metadata

title: Playwight 程式元件介紹
tags: [Playwright, End to End]

---

<style>
.center{
    display: flex;
    justify-content: center;
}
.txt_color{
    color: #224499;
}
.split_line{
    border-bottom-style: solid;
    border-width: 1px;
    border-color: #999999;
}
.txt_center{
    text-align: center;
}

.lighten_txt{
    color: #aa0000;
}
.red_txt{
    color: #DD2200;
}
</style>

# Playwight 程式元件介紹
### 程式碼中指定瀏覽器啟動
```python
from playwright.sync_api import sync_playwright

with sync_playwright() as playwright:
    browser = playwright.chromium.launch(headless=False)
    # firefox ↓
    # playwright.firefox.launch(headless=False)
    
    # webkit　↓
    # playwright.webkit.launch(headless=False)
    # 如果無法執行, 可能會需要安裝 sudo apt-get install gstreamer1.0-plugins-bad
    context = browser.new_context()
    page = context.new_page()
    page.goto("https://www.google.com/?hl=zh_tw")
    
    page.wait_for_timeout(timeout=2000)

    # Close page
    page.close()
    context.close()
    browser.close()
```


### 設定執行時不顯示畫面
```python
browser = playwright.chromium.launch(headless=True)
```



### 以較慢動作執行腳本
```python
browser = playwright.chromium.launch(headless=False, slow_mo=毫秒)
```


### 讀取 json cookie 狀態
```python
context = browser.new_context(storage_state="filename.json")
```


### 設定畫面尺寸
- 瀏覽器
    ```python
    context = browser.new_context(
        viewport={
            "width": 1920,
            "height": 1080
        })
    ```

- 單個分頁
    ```python
    ...
    page.set_viewport_size(
        viewport_size={
            "width": 1920,
            "height": 1080
        })
    page.goto("url")
    ```

- 指定手機尺寸
    ```python
    context = browser.new_context(
        **playwright.devices['Pixel 2'],
    )
    ```



### 程式中接續錄製腳本
==playwright.chromium.launch(headless=False) 的狀態才能進行錄製[才看的到畫面]==
```pyhton
# 在程式碼中要繼續錄製的部份加上
page.pause()
```



### 取得網頁元件的方式 - <span class="lighten_txt">query_selector</span>
- Text selector
- CSS selector
    - [css 元件補充](https://webdevsimplified.com/specificity-cheat-sheet.html)
- XPath selectors
    `找元件的輔助工具`
    - [X_Path_查詢](https://devhints.io/xpath)
    - [Google擴充-SelectorsHub](https://chrome.google.com/webstore/detail/selectorshub/ndgimibanhlabgdgjcpbbndiehljcpfh)
- Id selectors
  - id
  - data-testid
  - data-test-id
  - data-test


<div class="txt_color">透過 text 找目標元件</div>

```python
page.query_selector('元件:has-text("包含文字")') 
page.query_selector('css類別:text("包含文字")')
page.query_selector('元件>>text=包含文字')
```


<div class="txt_color">透過元件狀態[visible]找目標元件</div>

```python
page.query_selector("button:visible")
page.query_selector("button:visible:text('包含文字')")
```

<div class="txt_color">透過元件 id 找目標元件</div>

```python
page.query_selector(selector="#id")
```


[Element selectors](https://playwright.dev/python/docs/selectors)


### 取得元件-實際範例
:::spoiler
```script
from playwright.sync_api import sync_playwright


def run(playwright):
    browser = playwright.chromium.launch(headless=False, slow_mo=500)
    context = browser.new_context()
    page = context.new_page()
    page.goto("http://www.uitestingplayground.com/dynamicid")

    # 透過元件ID
    element_id = page.query_selector(selector="#b4d2b80c-2be1-6d56-4dba-21b02b696137")
    assert element_id is None

    # 透過 元件
    with_element_attribute = page.query_selector(selector="button:visible")
    element_attribute_with_text1 = page.query_selector(selector="button:visible:text('Button with Dynamic ID')")
    element_attribute_with_text2 = page.query_selector(selector="button>>text=Button with Dynamic ID")
    element_attribute_with_text3 = page.query_selector(selector="button:has-text('Button with Dynamic ID')")

    assert with_element_attribute.text_content() == element_attribute_with_text1.text_content() and \
           with_element_attribute.text_content() == element_attribute_with_text2.text_content() and \
           with_element_attribute.text_content() == element_attribute_with_text3.text_content()

    # 透過 css
    element_css = page.query_selector(selector=".btn-primary")
    element_css_with_text1 = page.query_selector(selector=".btn-primary:text('Button with Dynamic ID')")
    element_css_with_text2 = page.query_selector(selector=".btn-primary:has-text('Button with Dynamic ID')")

    assert element_css.text_content() == element_css_with_text1.text_content() and \
           element_css.text_content() == element_css_with_text2.text_content()

    context.close()
    browser.close()


def main():
    with sync_playwright() as playwright:
        run(playwright)


if __name__ == "__main__":
    main()
```
:::


### 對元件執行動作

#### 點擊元件 - <span class="lighten_txt">click</span>
```python
page.click(selector="")
```

#### 在輸入框輸入內容 - <span class="lighten_txt">fill, type</span>

- fill : <span class="red_txt">元件需要是 input, textarea 或 contenteditable</span>

```python
page.fill(selecetor="", value="")
```

- type : <span class="red_txt">模擬按鍵操作輸入內容</span>

```python
page.type(selecetor="", value="", delay=毫秒)
```

#### 勾選 CheckBox - <span class="lighten_txt">check, uncheck</span>
- 選取勾選選項
```python
page.check(selecetor="")
```
- 取消勾選選項
```python
page.unchecked(selecetor="")
```


#### 選取選單內容 - <span class="lighten_txt">select_option</span>
[官方文件說明](https://playwright.dev/python/docs/api/class-page/#page-select-option)
- 單選選單
```python
page.select_option(selector="", value="")
```
```python
page.select_option(selector="", label="")
```
- 多選選單
```python
page.select_option(selector="", value=["red", "green", "blue"])
```

<hr>

<!-- [End to End 目錄](https://hackmd.io/F41miM4aRP2eljbPy6grCg) -->

###### tags: `Playwright` `End to End`