python使用playwright
时间: 2023-10-11 11:14:33 浏览: 169
Playwright是一个Python库,可通过单个API自动化Chromium,Firefox和WebKit浏览器-Python开发
使用Playwright可以在Python脚本中进行自动化程序的编写。首先,需要通过pip命令安装Playwright。然后可以使用import语句导入Playwright库。根据个人喜好,可以选择启动chromium、firefox或webkit浏览器。以下是一个简单的示例代码,实现了控制chromium浏览器打开百度首页,并获取页面源码的title属性值并打印在Python控制台上:
```python
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("https://www.baidu.com/")
print(page.title())
browser.close()
```
请注意,默认情况下,Playwright以无头模式运行浏览器,所以并不会弹出浏览器界面。如果希望查看浏览器界面,可以在启动浏览器时传递`headless=False`参数。以下是示例代码:
```python
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
page.goto("https://www.baidu.com/")
print(page.title())
browser.close()
```
阅读全文