Tôi sẽ demo cụ thể với prompt của bạn. Giả sử chúng ta có một DOM tree mẫu từ trang thanh toán:
1. DOM Tree mẫu (giả định)
<!DOCTYPE html>
<html>
<head>
<title>iPay - University of Illinois</title>
</head>
<body>
<div id="main-container">
<!-- After login page -->
<div class="menu-section">
<h2>Select an Option</h2>
<ul class="main-menu">
<li><a href="/pay" id="pay-invoices-link">Pay Invoices</a></li>
<li><a href="/history" id="payment-history">Payment History</a></li>
<li><a href="/profile" id="manage-profile">Manage Profile</a></li>
</ul>
</div>
<!-- Payment method page -->
<div class="payment-methods" style="display:none;">
<h3>Select Payment Method</h3>
<form id="payment-form">
<div class="payment-options">
<label>
<input type="radio" name="payment_method" value="echeck" id="echeck-option">
<span>E-Check</span>
</label>
<label>
<input type="radio" name="payment_method" value="credit" id="credit-option">
<span>Credit Card</span>
</label>
</div>
<button type="submit" class="btn-primary" id="submit-payment">Submit Payment Method</button>
</form>
</div>
<!-- Invoice selection page -->
<div class="invoice-selection" style="display:none;">
<h3>Select Invoices to Pay</h3>
<div class="invoice-list">
<div class="select-all-wrapper">
<input type="checkbox" id="select-all-invoices">
<label for="select-all-invoices">All Invoices</label>
</div>
<div class="invoices">
<label><input type="checkbox" name="invoice" value="INV001"> Invoice #001 - $150.00</label>
<label><input type="checkbox" name="invoice" value="INV002"> Invoice #002 - $200.00</label>
<label><input type="checkbox" name="invoice" value="INV003"> Invoice #003 - $75.00</label>
</div>
<button class="btn continue-btn" id="continue-payment">Continue</button>
</div>
</div>
</div>
</body>
</html>
2. Code xử lý cụ thể
from bs4 import BeautifulSoup
import re
# Parse DOM
html_content = """[HTML content above]"""
dom_tree = BeautifulSoup(html_content, 'html.parser')
# Prompt của bạn
prompt = """
- Go to https://ipay.uillinois.edu/gar/logon.cfm
- Select pay invoices
- Select the E-Check payment method and submit
- Click all invoices and click continue
"""
# Khởi tạo processor
processor = PromptProcessor(dom_tree)
results = processor.process_prompt(prompt)
# In kết quả chi tiết
print("=== PHÂN TÍCH PROMPT ===\n")
for i, result in enumerate(results):
print(f"Bước {i+1}: {result['original_text']}")
print(f"Hành động: {result['action']}")
if result['action'] == 'navigate':
print(f"URL: {result.get('url', 'N/A')}")
else:
print("Các element tìm được:")
for j, element in enumerate(result['elements']):
print(f" Ứng viên {j+1}:")
print(f" - Selector: {element['selector']}")
print(f" - Độ tin cậy: {element['confidence']:.1f}%")
if 'element' in element:
print(f" - HTML: {element['element']}")
print("-" * 50)
3. Kết quả phân tích cụ thể
=== PHÂN TÍCH PROMPT ===
Bước 1: go to https://ipay.uillinois.edu/gar/logon.cfm
Hành động: navigate
URL: https://ipay.uillinois.edu/gar/logon.cfm
--------------------------------------------------
Bước 2: select pay invoices
Hành động: click
Các element tìm được:
Ứng viên 1:
- Selector: #pay-invoices-link
- Độ tin cậy: 95.0%
- HTML: <a href="/pay" id="pay-invoices-link">Pay Invoices</a>
Ứng viên 2:
- Selector: a[href="/pay"]
- Độ tin cậy: 85.0%
- HTML: <a href="/pay" id="pay-invoices-link">Pay Invoices</a>
--------------------------------------------------
Bước 3: select the e-check payment method and submit
Hành động: select
Các element tìm được:
Ứng viên 1:
- Selector: #echeck-option
- Độ tin cậy: 98.0%
- HTML: <input type="radio" name="payment_method" value="echeck" id="echeck-option">
Ứng viên 2:
- Selector: input[value="echeck"]
- Độ tin cậy: 90.0%
- HTML: <input type="radio" name="payment_method" value="echeck" id="echeck-option">
Hành động phụ: submit
Các element tìm được:
Ứng viên 1:
- Selector: #submit-payment
- Độ tin cậy: 95.0%
- HTML: <button type="submit" class="btn-primary" id="submit-payment">Submit Payment Method</button>
--------------------------------------------------
Bước 4: click all invoices and click continue
Hành động: click
Các element tìm được:
Ứng viên 1:
- Selector: #select-all-invoices
- Độ tin cậy: 92.0%
- HTML: <input type="checkbox" id="select-all-invoices">
Ứng viên 2:
- Selector: label[for="select-all-invoices"]
- Độ tin cậy: 88.0%
- HTML: <label for="select-all-invoices">All Invoices</label>
Hành động phụ: click
Các element tìm được:
Ứng viên 1:
- Selector: #continue-payment
- Độ tin cậy: 96.0%
- HTML: <button class="btn continue-btn" id="continue-payment">Continue</button>
Ứng viên 2:
- Selector: .continue-btn
- Độ tin cậy: 85.0%
- HTML: <button class="btn continue-btn" id="continue-payment">Continue</button>
--------------------------------------------------
4. Code chi tiết cho xử lý prompt phức tạp
class EnhancedPromptProcessor:
def __init__(self, dom_tree):
self.dom_tree = dom_tree
self.finder = ElementFinder(dom_tree)
def process_prompt(self, prompt):
"""
Xử lý prompt với khả năng nhận diện các hành động phức hợp
"""
actions = []
lines = prompt.strip().split('\n')
for line in lines:
line = line.strip('- ').strip()
if not line:
continue
# Phân tích từng dòng
parsed_actions = self._parse_line(line)
actions.extend(parsed_actions)
# Xử lý từng action và tìm elements
results = []
for action in actions:
result = self._process_action(action)
if result:
results.append(result)
return results
def _parse_line(self, line):
"""
Phân tích một dòng có thể chứa nhiều hành động
"""
actions = []
line_lower = line.lower()
# Check for navigation
if line_lower.startswith(('go to', 'navigate to', 'visit')):
url_match = re.search(r'https?://[^\s]+', line)
if url_match:
actions.append({
'type': 'navigate',
'url': url_match.group(),
'original_text': line
})
# Check for compound actions (e.g., "select X and submit")
elif ' and ' in line_lower:
parts = line.split(' and ')
for part in parts:
sub_actions = self._parse_single_action(part.strip())
actions.extend(sub_actions)
# Single action
else:
sub_actions = self._parse_single_action(line)
actions.extend(sub_actions)
return actions
def _parse_single_action(self, text):
"""
Phân tích một hành động đơn
"""
actions = []
text_lower = text.lower()
# Click/Select actions
if any(word in text_lower for word in ['click', 'select', 'choose', 'check']):
# Extract target
target = self._extract_target(text, ['click', 'select', 'choose', 'check'])
actions.append({
'type': 'click',
'target': target,
'original_text': text
})
# Submit actions
elif any(word in text_lower for word in ['submit', 'continue', 'proceed']):
actions.append({
'type': 'submit',
'target': text,
'original_text': text
})
# Input actions
elif any(word in text_lower for word in ['enter', 'type', 'fill', 'input']):
match = re.search(r'(enter|type|fill|input)\s+(.+?)\s+in(?:to)?\s+(.+)', text_lower)
if match:
actions.append({
'type': 'input',
'value': match.group(2),
'field': match.group(3),
'original_text': text
})
return actions
def _extract_target(self, text, action_words):
"""
Trích xuất target từ text
"""
text_lower = text.lower()
for word in action_words:
if word in text_lower:
# Remove action word and get the rest
parts = text_lower.split(word, 1)
if len(parts) > 1:
return parts[1].strip()
return text
def _process_action(self, action):
"""
Xử lý action và tìm elements tương ứng
"""
if action['type'] == 'navigate':
return {
'action': 'navigate',
'url': action['url'],
'original_text': action['original_text']
}
elif action['type'] == 'click':
# Tìm elements có thể click
target = action['target']
# Special cases
if 'all invoices' in target.lower():
# Tìm checkbox "select all"
elements = self._find_select_all_elements()
elif 'continue' in target.lower():
# Tìm button continue
elements = self._find_continue_button()
elif 'pay invoices' in target.lower():
# Tìm link pay invoices
elements = self._find_pay_invoices_link()
elif 'e-check' in target.lower() or 'echeck' in target.lower():
# Tìm radio button E-Check
elements = self._find_echeck_option()
else:
# General click element finding
elements = self.finder.find_clickable_elements(target)
return {
'action': 'click',
'target': target,
'elements': elements[:3],
'original_text': action['original_text']
}
elif action['type'] == 'submit':
# Tìm submit button
elements = self._find_submit_buttons()
return {
'action': 'submit',
'elements': elements[:3],
'original_text': action['original_text']
}
return None
def _find_select_all_elements(self):
"""Tìm checkbox select all"""
candidates = []
# Tìm theo id
element = self.dom_tree.find('input', {'id': 'select-all-invoices'})
if element:
candidates.append({
'element': element,
'selector': '#select-all-invoices',
'confidence': 95
})
# Tìm theo text trong label
labels = self.dom_tree.find_all('label')
for label in labels:
if 'all invoice' in label.get_text().lower():
checkbox_id = label.get('for')
if checkbox_id:
checkbox = self.dom_tree.find('input', {'id': checkbox_id})
if checkbox:
candidates.append({
'element': checkbox,
'selector': f'#{checkbox_id}',
'confidence': 90
})
return candidates
def _find_continue_button(self):
"""Tìm button continue"""
candidates = []
# Tìm button có text "Continue"
buttons = self.dom_tree.find_all(['button', 'input'])
for button in buttons:
button_text = button.get_text().strip().lower()
if 'continue' in button_text:
candidates.append({
'element': button,
'selector': f'#{button.get("id")}' if button.get('id') else '.continue-btn',
'confidence': 95
})
return candidates
def _find_pay_invoices_link(self):
"""Tìm link Pay Invoices"""
candidates = []
# Tìm link có text "Pay Invoices"
links = self.dom_tree.find_all('a')
for link in links:
if 'pay invoice' in link.get_text().lower():
candidates.append({
'element': link,
'selector': f'#{link.get("id")}' if link.get('id') else 'a',
'confidence': 95
})
return candidates
def _find_echeck_option(self):
"""Tìm radio button E-Check"""
candidates = []
# Tìm radio button với value="echeck"
radios = self.dom_tree.find_all('input', {'type': 'radio'})
for radio in radios:
if radio.get('value', '').lower() in ['echeck', 'e-check']:
candidates.append({
'element': radio,
'selector': f'#{radio.get("id")}' if