-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathbrowser.py
More file actions
394 lines (325 loc) · 15.1 KB
/
browser.py
File metadata and controls
394 lines (325 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import os
import re
import json
from pathlib import Path
from browser_use.llm.openai.chat import ChatOpenAI
from browser_use.controller.service import Controller
from browser_use.filesystem.file_system import FileSystem
from browser_use.controller.views import ClickElementAction
from browser_use.controller.registry.views import ActionModel
from browser_use.browser import BrowserProfile, BrowserSession
from browser_use.config import get_default_profile, load_browser_use_config, get_default_llm, FlatEnvConfig
class BrowserUse:
def __init__(self):
self.config = load_browser_use_config()
self.browser_session: BrowserSession | None = None
self.controller: Controller | None = None
# self.file_system: FileSystem | None = None
self.llm: ChatOpenAI | None = None
# TODO: Need to expose more path parameters to initialization
async def _init_browser_session(self, **kwargs):
"""Initialize browser session using config"""
if self.browser_session:
return
# Get profile config
# profile_config = get_default_profile(self.config)
# Merge profile config with defaults and overrides
profile_data = {
'downloads_path': '/workspace/downloads',
'wait_between_actions': 0.5,
'keep_alive': True,
'user_data_dir': '~/.config/browseruse/profiles/default',
'is_mobile': False,
'device_scale_factor': 1.0,
'disable_security': False,
# 'headless': True,
"default": True,
"allowed_domains": None,
# **profile_config, # Config values override defaults
}
# Merge any additional kwargs that are valid BrowserProfile fields
for key, value in kwargs.items():
profile_data[key] = value
# Create browser profile
profile = BrowserProfile(**profile_data)
# Create browser session
self.browser_session = BrowserSession(browser_profile=profile)
await self.browser_session.start()
# Create controller for direct actions
self.controller = Controller()
self.llm = ChatOpenAI(
model='gemini-2.5-pro',
api_key=os.getenv('API_KEY'),
base_url=os.getenv('BASE_URL'),
temperature=0.7,
# max_tokens=llm_config.get('max_tokens'),
)
# Initialize FileSystem for extraction actions
file_system_path = profile_data.get('file_system_path', '/workspace/browser-use')
self.file_system = FileSystem(base_dir=Path(file_system_path).expanduser())
async def get_axtree(self):
page = await self.browser_session.get_current_page()
cdp_session = await page.context.new_cdp_session(page)
await cdp_session.send('Accessibility.enable')
await cdp_session.send('DOM.enable')
ax_tree = await cdp_session.send('Accessibility.getFullAXTree')
return flatten_axtree_to_str(ax_tree)
async def get_browser_state(self) -> str:
"""Get current browser state."""
if not self.browser_session:
return 'Error: No browser session active, please use go to a url'
state = await self.browser_session.get_state_summary(cache_clickable_elements_hashes=False)
result = {
'url': state.url,
'title': state.title,
'tabs': [{'url': tab.url, 'title': tab.title} for tab in state.tabs],
'interactive_elements': [],
}
# Add interactive elements with their indices
for index, element in state.selector_map.items():
raw_str = element.clickable_elements_to_string().replace('\t', '').replace('\n[', '[')
all_indices = [int(x) for x in re.findall(r'\[(\d+)\]', raw_str)]
# main_idx = all_indices[0] if all_indices else None
sub_element_indices = all_indices[1:] if len(all_indices) > 1 else []
main_tag_match = re.search(r'\[\d+\]<(.*?)\/>', raw_str)
main_tag_text = '<' + main_tag_match.group(1).strip() + '/>' if main_tag_match else ""
elem_info = {
'index': index,
'tag': element.tag_name,
'text': main_tag_text,
# 'sub_element_index': sub_element_indices,
}
if element.attributes.get('placeholder'):
elem_info['placeholder'] = element.attributes['placeholder']
if element.attributes.get('href'):
elem_info['href'] = element.attributes['href']
result['interactive_elements'].append(elem_info)
return json.dumps(result["interactive_elements"])
async def extract_content_by_vision(self, query: str) -> str:
state = await self.browser_session.get_state_summary(cache_clickable_elements_hashes=False)
response = await self.llm.get_client().chat.completions.create(
model=self.llm.model,
messages=[
{"role": "user", "content": [
{"type": "text", "text": query},
{
"type": "image_url",
"image_url": {"url": f"data:image/jpeg;base64,{state.screenshot}"}
}
]}
]
)
await self.browser_session.remove_highlights()
return response.choices[0].message.content
async def go_to_url(self, url: str, new_tab: bool):
if not self.browser_session:
await self._init_browser_session()
action = self.controller.registry.create_action_model()(go_to_url={"url": url, "new_tab": new_tab})
action_result = await self.controller.act(
action=action,
browser_session=self.browser_session,
file_system=self.file_system,
)
await self.browser_session.remove_highlights()
if action_result.error is None:
return action_result.extracted_content
else:
return "ERROR: " + action_result.error
async def wait(self, seconds: int):
if not self.browser_session:
return 'Error: No browser session active, please use go to a url'
action = self.controller.registry.create_action_model()(wait={"seconds": seconds})
action_result = await self.controller.act(
action=action,
browser_session=self.browser_session,
file_system=self.file_system,
)
await self.browser_session.remove_highlights()
if action_result.error is None:
return action_result.extracted_content
else:
return "ERROR: " + action_result.error
async def click_element_by_index(self, index: int):
if not self.browser_session:
return 'Error: No browser session active, please use go to a url'
action = self.controller.registry.create_action_model()(click_element_by_index={"index": index})
action_result = await self.controller.act(
action=action,
browser_session=self.browser_session,
file_system=self.file_system,
)
await self.browser_session.remove_highlights()
if action_result.error is None:
return action_result.extracted_content
else:
return "ERROR: " + action_result.error
async def input_text(self, index: int, text: str):
if not self.browser_session:
return 'Error: No browser session active, please use go to a url'
action = self.controller.registry.create_action_model()(input_text={"index": index, "text": text})
action_result = await self.controller.act(
action=action,
browser_session=self.browser_session,
file_system=self.file_system,
)
await self.browser_session.remove_highlights()
if action_result.error is None:
return action_result.extracted_content
else:
return "ERROR: " + action_result.error
async def send_keys(self, keys: str):
if not self.browser_session:
return 'Error: No browser session active, please use go to a url'
action = self.controller.registry.create_action_model()(send_keys={"keys": keys})
action_result = await self.controller.act(
action=action,
browser_session=self.browser_session,
file_system=self.file_system,
)
await self.browser_session.remove_highlights()
if action_result.error is None:
return action_result.extracted_content
else:
return "ERROR: " + action_result.error
async def upload_file(self, index: int, path: str):
if not self.browser_session:
return 'Error: No browser session active, please use go to a url'
action = self.controller.registry.create_action_model()(upload_file={"index": index, "path": path})
action_result = await self.controller.act(
action=action,
browser_session=self.browser_session,
file_system=self.file_system,
)
await self.browser_session.remove_highlights()
if action_result.error is None:
return action_result.extracted_content
else:
return "ERROR: " + action_result.error
async def go_back(self):
if not self.browser_session:
return 'Error: No browser session active, please use go to a url'
action = self.controller.registry.create_action_model()(go_back={})
action_result = await self.controller.act(
action=action,
browser_session=self.browser_session,
file_system=self.file_system,
)
await self.browser_session.remove_highlights()
if action_result.error is None:
return action_result.extracted_content
else:
return "ERROR: " + action_result.error
async def scroll(self, down: bool, num_pages: float, index: int):
if not self.browser_session:
return 'Error: No browser session active, please use go to a url'
action = self.controller.registry.create_action_model()(scroll={"down": down, "num_pages": num_pages, "index": index})
action_result = await self.controller.act(
action=action,
browser_session=self.browser_session,
file_system=self.file_system,
)
await self.browser_session.remove_highlights()
if action_result.error is None:
return action_result.extracted_content
else:
return "ERROR: " + action_result.error
async def list_tabs(self):
if not self.browser_session:
return 'Error: No browser session active, please use go to a url'
state = await self.browser_session.get_state_summary(cache_clickable_elements_hashes=False)
tabs = [{'index': tab.page_id, 'url': tab.url, 'title': tab.title} for tab in state.tabs]
await self.browser_session.remove_highlights()
return tabs
async def switch_tab(self, tab_index: int,):
if not self.browser_session:
return 'Error: No browser session active, please use go to a url'
action = self.controller.registry.create_action_model()(switch_tab={"page_id": tab_index})
action_result = await self.controller.act(
action=action,
browser_session=self.browser_session,
file_system=self.file_system,
)
await self.browser_session.remove_highlights()
if action_result.error is None:
return action_result.extracted_content
else:
return "ERROR: " + action_result.error
async def close_tab(self, tab_index: int):
if not self.browser_session:
return 'Error: No browser session active, please use go to a url'
action = self.controller.registry.create_action_model()(close_tab={"page_id": tab_index})
action_result = await self.controller.act(
action=action,
browser_session=self.browser_session,
file_system=self.file_system,
)
await self.browser_session.remove_highlights()
if action_result.error is None:
return action_result.extracted_content
else:
return "ERROR: " + action_result.error
async def get_dropdown_options(self, index: int):
if not self.browser_session:
return 'Error: No browser session active, please use go to a url'
action = self.controller.registry.create_action_model()(get_dropdown_options={"index": index})
action_result = await self.controller.act(
action=action,
browser_session=self.browser_session,
file_system=self.file_system,
)
await self.browser_session.remove_highlights()
if action_result.error is None:
return action_result.extracted_content
else:
return "ERROR: " + action_result.error
async def select_dropdown_option(self, index: int, text: str):
if not self.browser_session:
return 'Error: No browser session active, please use go to a url'
action = self.controller.registry.create_action_model()(select_dropdown_option={"index": index, "text": text})
action_result = await self.controller.act(
action=action,
browser_session=self.browser_session,
file_system=self.file_system,
)
await self.browser_session.remove_highlights()
if action_result.error is None:
return action_result.extracted_content
else:
return "ERROR: " + action_result.error
# ========================================================================= #
# UTILS
# ========================================================================= #
def flatten_axtree_to_str(axtree, ignored_roles=None, depth=0, node_idx=0):
if ignored_roles is None:
ignored_roles = {"none"}
nodes = axtree["nodes"]
node = nodes[node_idx]
role = node.get("role", {}).get("value", "")
name = node.get("name", {}).get("value", "")
if node.get("ignored", False) or role in ignored_roles:
children_str = ""
for child_id in node.get("childIds", []):
child_idx = next((i for i, n in enumerate(nodes) if n["nodeId"] == child_id), None)
if child_idx is not None:
children_str += flatten_axtree_to_str(axtree, ignored_roles, depth, child_idx)
return children_str
indent = " " * depth
props = []
for prop in node.get("properties", []):
p_name = prop.get("name", "")
p_val_dict = prop.get("value")
if p_val_dict is not None:
if isinstance(p_val_dict, dict) and "value" in p_val_dict:
p_value = p_val_dict["value"]
else:
p_value = p_val_dict
else:
p_value = None
props.append(f"{p_name}={repr(p_value)}")
prop_str = (", " + ", ".join(props)) if props else ""
s = f"{indent}{role} {repr(name)}{prop_str}\n"
for child_id in node.get("childIds", []):
child_idx = next((i for i, n in enumerate(nodes) if n["nodeId"] == child_id), None)
if child_idx is not None:
s += flatten_axtree_to_str(axtree, ignored_roles, depth+1, child_idx)
return s