Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Improve file upload detection
Evgeny Kim5da261310ba6
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 126ea26a0..ab995641d 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -1925,32 +1925,93 @@ class BrowserSession(BaseModel):return element_handle@require_initialization- async def is_file_uploader(self, element_node: DOMElementNode, max_depth: int = 3, current_depth: int = 0) -> bool:- """Check if element or its children are file uploaders"""- if current_depth > max_depth:- return False-- # Check current element- is_uploader = False-- if not isinstance(element_node, DOMElementNode):- return False-- # Check for file input attributes- if element_node.tag_name == 'input':- is_uploader = element_node.attributes.get('type') == 'file' or element_node.attributes.get('accept') is not None-- if is_uploader:- return True-- # Recursively check children- if element_node.children and current_depth < max_depth:- for child in element_node.children:- if isinstance(child, DOMElementNode):- if await self.is_file_uploader(child, max_depth, current_depth + 1):- return True-- return False+ async def find_file_upload_element_by_index(self, index: int) -> DOMElementNode | None:+ """+ Find a file upload element related to the element at the given index:+ - Check if the element itself is a file input+ - Check if it's a label pointing to a file input+ - Recursively search children for file inputs+ - Check siblings for file inputs++ Args:+ index: The index of the candidate element (could be a file input, label, or parent element)++ Returns:+ The DOM element for the file input if found, None otherwise+ """+ try:+ selector_map = await self.get_selector_map()+ if index not in selector_map:+ return None++ candidate_element = selector_map[index]++ def is_file_input(node: DOMElementNode) -> bool:+ return isinstance(node, DOMElementNode) and node.tag_name == 'input' and node.attributes.get('type') == 'file'++ def find_element_by_id(node: DOMElementNode, element_id: str) -> DOMElementNode | None:+ if isinstance(node, DOMElementNode):+ if node.attributes.get('id') == element_id:+ return node+ for child in node.children:+ result = find_element_by_id(child, element_id)+ if result:+ return result+ return None++ def get_root(node: DOMElementNode) -> DOMElementNode:+ root = node+ while root.parent:+ root = root.parent+ return root++ # Recursively search for file input in node and its children+ def find_file_input_recursive(node: DOMElementNode, max_depth: int = 3, current_depth: int = 0) -> DOMElementNode | None:+ if current_depth > max_depth or not isinstance(node, DOMElementNode):+ return None++ # Check current element+ if is_file_input(node):+ return node++ # Recursively check children+ if node.children and current_depth < max_depth:+ for child in node.children:+ if isinstance(child, DOMElementNode):+ result = find_file_input_recursive(child, max_depth, current_depth + 1)+ if result:+ return result+ return None++ # Check if current element is a file input+ if is_file_input(candidate_element):+ return candidate_element++ # Check if it's a label pointing to a file input+ if candidate_element.tag_name == 'label' and candidate_element.attributes.get('for'):+ input_id = candidate_element.attributes.get('for')+ root_element = get_root(candidate_element)++ target_input = find_element_by_id(root_element, input_id)+ if target_input and is_file_input(target_input):+ return target_input++ # Recursively check children+ child_result = find_file_input_recursive(candidate_element)+ if child_result:+ return child_result++ # Check siblings+ if candidate_element.parent:+ for sibling in candidate_element.parent.children:+ if sibling is not candidate_element and isinstance(sibling, DOMElementNode):+ if is_file_input(sibling):+ return sibling+ return None++ except Exception as e:+ logger.debug(f"Error in find_file_upload_element_by_index: {e}")+ return None@require_initializationasync def get_scroll_info(self, page: Page) -> tuple[int, int]:diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex 16a8f59c6..e57fc747e 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -135,7 +135,7 @@ class Controller(Generic[Context]):initial_pages = len(browser_session.tabs)# if element has file uploader then dont click- if await browser_session.is_file_uploader(element_node):+ if await browser_session.find_file_upload_element_by_index(params.index) is not None:msg = f'Index {params.index} - has an element which opens file upload dialog. To upload files please use a specific function to upload files 'logger.info(msg)return ActionResult(extracted_content=msg, include_in_memory=True)diff --git a/browser_use/dom/buildDomTree.js b/browser_use/dom/buildDomTree.jsindex fe8d18f58..2ac63dbea 100644--- a/browser_use/dom/buildDomTree.js+++ b/browser_use/dom/buildDomTree.js@@ -993,7 +993,7 @@// Fast-path for common interactive elementsconst interactiveElements = new Set([- "a", "button", "input", "select", "textarea", "details", "summary"+ "a", "button", "input", "select", "textarea", "details", "summary", "label"]);if (interactiveElements.has(tagName)) return true;diff --git a/browser_use/dom/views.py b/browser_use/dom/views.pyindex 0a7076b54..e96723068 100644--- a/browser_use/dom/views.py+++ b/browser_use/dom/views.py@@ -233,28 +233,6 @@ class DOMElementNode(DOMBaseNode):process_node(self, 0)return '\n'.join(formatted_text)- def get_file_upload_element(self, check_siblings: bool = True) -> Optional['DOMElementNode']:- # Check if current element is a file input- if self.tag_name == 'input' and self.attributes.get('type') == 'file':- return self-- # Check children- for child in self.children:- if isinstance(child, DOMElementNode):- result = child.get_file_upload_element(check_siblings=False)- if result:- return result-- # Check siblings only for the initial call- if check_siblings and self.parent:- for sibling in self.parent.children:- if sibling is not self and isinstance(sibling, DOMElementNode):- result = sibling.get_file_upload_element(check_siblings=False)- if result:- return result-- return None-SelectorMap = dict[int, DOMElementNode]diff --git a/examples/custom-functions/file_upload.py b/examples/custom-functions/file_upload.pyindex 2fcd90a67..4301ca3db 100644--- a/examples/custom-functions/file_upload.py+++ b/examples/custom-functions/file_upload.py@@ -37,9 +37,7 @@ async def upload_file(index: int, path: str, browser_session: BrowserSession, avif not os.path.exists(path):return ActionResult(error=f'File {path} does not exist')- dom_el = await browser_session.get_dom_element_by_index(index)-- file_upload_dom_el = dom_el.get_file_upload_element()+ file_upload_dom_el = await browser_session.find_file_upload_element_by_index(index)if file_upload_dom_el is None:msg = f'No file upload element found at index {index}'diff --git a/examples/use-cases/find_and_apply_to_jobs.py b/examples/use-cases/find_and_apply_to_jobs.pyindex de2984e6d..c6a01b270 100644--- a/examples/use-cases/find_and_apply_to_jobs.py+++ b/examples/use-cases/find_and_apply_to_jobs.py@@ -80,12 +80,7 @@ def read_cv():)async def upload_cv(index: int, browser_session: BrowserSession):path = str(CV.absolute())- dom_el = await browser_session.get_dom_element_by_index(index)-- if dom_el is None:- return ActionResult(error=f'No element found at index {index}')-- file_upload_dom_el = dom_el.get_file_upload_element()+ file_upload_dom_el = await browser_session.find_file_upload_element_by_index(index)if file_upload_dom_el is None:logger.info(f'No file upload element found at index {index}')