ichrome库操作浏览器

启动一个 Chrome 实例,连接到第一个标签页,并打开百度网页。

通过 js() 方法,在页面中选中了一个复选框和一个输入框,并设置了它们的值。

点击页面中的提交按钮,等待5秒钟,然后使用正则表达式提取页面中的 JSON 数据。

最后,通过 repl() 方法进入交互式模式,可以在命令行中查看标签页的 URL 等信息。
具体注释如下:

import asyncio import json from ichrome import AsyncChromeDaemon async def main(): # 创建 AsyncChromeDaemon 对象,并设置一些参数 async with AsyncChromeDaemon(clear_after_shutdown=True, # 关闭标签页后清除缓存 headless=False, # 不使用无头模式 disable_image=False, # 不禁用图片加载 user_data_dir='./ichrome_user_data' # 用户数据目录 ) as cd: # 连接到第一个标签页,并自动关闭 async with cd.connect_tab(0, auto_close=True) as tab: # 打开百度网页,等待10秒钟 loaded = await tab.goto('https://baidu.com', timeout=10) # 获取页面 HTML 和标题 html = await tab.html title = await tab.title # 打印页面加载情况、HTML 长度和标题 print( f'page loaded ok: {loaded}, HTML length is {len(html)}, title is "{title}"' ) # 选中一个复选框和一个输入框,并设置它们的值 await tab.js( r'''document.querySelector('[value="bacon"]').checked = true''') # 选中一个复选框 await tab.click('[value="cheese"]') # 点击一个复选框 await tab.js( r'''document.querySelector('[name="custname"]').value = "1234"''' ) # 设置一个输入框的值 # 点击提交按钮,等待5秒钟 await tab.click('form button') await tab.wait_loading(5) # 使用正则表达式提取页面中的 JSON 数据 result = await tab.findone(r'<pre.*?>([\s\S]*?)</pre>') print(result) # 进入交互式模式,可以在命令行中查看标签页的 URL 等信息。 await tab.repl() if __name__ == "__main__": asyncio.run(main())

需要注意的是,ichrome 库的一些方法都是异步方法,需要使用 async with 或 await 等关键字来调用。另外,AsyncChromeDaemon 对象是一个上下文管理器,需要使用 async with 语句创建。在程序结束时,会自动关闭 Chrome 实例并清除缓存。


  目录