1. 程式人生 > 其它 >Python自動化神器Playwright使用

Python自動化神器Playwright使用


安裝
```
pip install playwright
playwright install
```
用法
```
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto("http://playwright.dev")
    print(page.title())
    browser.close()
```
注意事項
1.Response.body()用法
-返回帶有響應正文的緩衝區
```
from playwright.sync_api import sync_playwright, Response

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    response = page.goto(url)
    response_decode = Response.body(response).decode(encoding="UTF-8")
```
注意:使用Response.body()需要import Response;
官方文件response.body()寫法錯誤,r應該為大寫,且需要一個引數
2.返回當前頁面資源
```
response = page.reload(**kwargs)
```
3.獲取元素邊界值
```
box = page.locator("text=請按住滑塊,拖動到最右邊").bounding_box()
```
4.特殊按鍵
The Meta key. Allows issuing special command inputs. This is the Windows logo key, or the Command or ⌘ key on Mac keyboards.
5.除錯
可以在語句中加入page.pause()來設定斷點,可以在斷點處人機互動解決問題,比如輸入驗證碼。重新載入正常網頁後,可以在playwright inspect中點選resume繼續執行剩餘程式碼。
6.滾動頁面
```
page.evaluate("window.scrollBy(x, y)") #滾動偏移量

page.evaluate("window.scrollTo(x, y)") #滾動到指定座標
```
參考1:https://github.com/microsoft/playwright-python/issues/902

參考2:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/scrollBy
7.要在瀏覽器上下文中計算的JavaScript表示式
```
page.evaluate(表示式,**kwargs
```