PlayWright(二)- 如何使用playwright
上篇我们已经安装好了playwright和各个浏览器,那么现在我们直接开始吧
1、怎么使用playwright?
我们需要先导入sync_playwright,然后用start启动,stop关闭
直接举例
使用谷歌浏览器打开百度网页
from playwright.sync_api import sync_playwright # 先导包 playwright = sync_playwright().start() # 创建playwright对象 browser = playwright.chromium.launch(headless=False) # 启动谷歌浏览器赋值给对象 page = browser.new_page() # 打开一个页面 page.goto('https://www.baidu.com/') # 打开百度地址 browser.close() # 关闭浏览器对象 playwright.stop() # 关闭playwright对象释放资源
上述是跟selenium同样的,都属于同步运行,playwright有2种运行方式:同步和异步
与selenium不同,我们不需要在使用浏览器驱动,直接创建playwright对象,然后启动对应浏览器
(playwright默认是无头模式启动,意思我们默认看不到浏览器的界面,想要查看浏览器界面,直接headless = False )
2、等待机制
与selenium不同,在playwright中不需要在使用time.sleep(),来设置等待时间
通过slow_mo (单位是毫秒)减少每个动作的等待时间,作用范围是全局,意思是操作元素一个动作就等待时间完毕后然后接着操作下一个动作,设置这个方便我们调试
这个在启动浏览器的时候,直接设置slow_mo = 3000
from playwright.sync_api import sync_playwright # 先导包
playwright = sync_playwright().start() # 创建playwright对象
browser = playwright.chromium.launch(headless=False,slow_mo =5000) # 启动谷歌浏览器赋值给对象
page = browser.new_page() # 打开一个页面
page.goto('https://www.baidu.com/') # 打开百度地址
browser.close() # 关闭浏览器对象
playwright.stop() # 关闭playwright对象释放资源
playwright的等待还有很多,后续我们在详细讲解
小练习:
打开微博,设置等每步等待5s