browser-use 库网页元素点击测试工具

发布于:2025-04-01 ⋅ 阅读:(25) ⋅ 点赞:(0)

代码

import asyncio
import json

from browser_use.browser.browser import Browser, BrowserConfig
from browser_use.dom.views import DOMBaseNode, DOMElementNode, DOMTextNode
from browser_use.utils import time_execution_sync


class ElementTreeSerializer:
	@staticmethod
	def dom_element_node_to_json(element_tree: DOMElementNode) -> dict:
		def node_to_dict(node: DOMBaseNode) -> dict:
			if isinstance(node, DOMTextNode):
				return {'type': 'text', 'text': node.text}
			elif isinstance(node, DOMElementNode):
				return {
					'type': 'element',
					'tag_name': node.tag_name,
					'attributes': node.attributes,
					'highlight_index': node.highlight_index,
					'children': [node_to_dict(child) for child in node.children],
				}
			return {}

		return node_to_dict(element_tree)


async def highlight_elements():
    browser = Browser(config=BrowserConfig(
        browser_instance_path=r"C:\Program Files\Google\Chrome\Application\chrome.exe",
        headless=False, disable_security=True))

    async with await browser.new_context() as context:
        page = await context.get_current_page()
        await page.goto('https://huggingface.co/')

        await asyncio.sleep(1)

        while True:
            try:
                state = await context.get_state()

                with open('./tmp/page.json', 'w') as f:
                    json.dump(
                        ElementTreeSerializer.dom_element_node_to_json(state.element_tree),
                        f,
                        indent=1,
                    )

                xpath_counts = {}
                if not state.selector_map:
                    continue
                for selector in state.selector_map.values():
                    xpath = selector.xpath
                    if xpath in xpath_counts:
                        xpath_counts[xpath] += 1
                    else:
                        xpath_counts[xpath] = 1

                print('\nDuplicate XPaths found:')
                for xpath, count in xpath_counts.items():
                    if count > 1:
                        print(f'XPath: {xpath}')
                        print(f'Count: {count}\n')

                print(list(state.selector_map.keys()), 'Selector map keys')
                print(state.element_tree.clickable_elements_to_string())
                action = input('Select next action: ')

                await time_execution_sync('remove_highlight_elements')(context.remove_highlights)()

                node_element = state.selector_map[int(action)]
				
                print(node_element)
				# <a class="group flex items-center px-2 py-0.5 dark:text-gray-300 dark:hover:text-gray-100" href="/models"> [interactive, top, highlight:4, in-viewport]
                result = await context._click_element_node(node_element)

            except Exception as e:
                print(e)
                await browser.close()
                break
        

if __name__ == '__main__':
    asyncio.run(highlight_elements())

代码解释

  1. 主要类和工具:
class ElementTreeSerializer:
    # 将DOM元素树序列化为JSON格式的工具类
    # 用于保存页面元素结构到文件
  1. 主要功能函数 highlight_elements()
  • 初始化浏览器:

    browser = Browser(config=BrowserConfig(
        browser_instance_path=r"C:\Program Files\Google\Chrome\Application\chrome.exe",
        headless=False, disable_security=True))
    

    创建一个可视化的Chrome浏览器实例

  • 页面操作循环:

    1. 获取页面状态:state = await context.get_state()
    2. 将页面DOM结构保存到./tmp/page.json
    3. 检查XPath重复情况并打印
    4. 显示可点击元素列表
    5. 等待用户输入要点击的元素序号
    6. 移除之前的高亮
    7. 执行点击操作
  1. 主要流程:
while True:
    try:
        # 1. 获取并展示页面元素
        # 2. 等待用户选择要点击的元素
        # 3. 执行点击操作
    except Exception:
        # 发生错误时关闭浏览器并退出
  1. 使用方式:
  • 运行脚本后会打开huggingface.co网站
  • 显示可点击元素列表
  • 用户输入数字选择要点击的元素
  • 程序执行点击并等待页面响应

这是一个交互式测试工具,用于:

  1. 验证元素定位功能
  2. 测试点击操作
  3. 检查页面响应
  4. 调试DOM元素选择器

主要用于开发和测试自动化浏览器操作功能。

输出结果

请添加图片描述
请添加图片描述


网站公告

今日签到

点亮在社区的每一天
去签到