因此,我正在尝试查看一个网页,当出现输入表单时,我需要输入我的姓名。我提出了这一点,但显然是不正确的。
tell application "Google Chrome"
set textToType to "Peter"
repeat
if execute javascript "document.getElementById('Account_UserName') then
execute javascript "document.getElementById('Account_UserName').focus();"
keystroke textToType
keystroke return
end if
end repeat
end tell发布于 2014-05-05 07:37:27
我使用此页面进行测试:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Test Page</title>
<style>
body {
margin: 10em;
padding: 2em;
border: solid .2em green;
}
h1 {
text-align: center;
}
</style>
</head>
<body>
<h1>Test Page</h1>
<form action="http://www.example.com/">
<input type="text" name="Account_UserName" id="Account_UserName">
</form>
</body>
</html>第一个问题是,为了聚焦,Chrome似乎需要指定的选项卡/窗口组合。因此,不是“执行javascript”,而是“执行tabSpecifier javascript”。
第二个问题是AppleScript需要一个布尔值来检查;它似乎不能很好地处理“execute javascript”的返回值。
第三个问题是,如果循环中没有延迟,AppleScript将锁定应用程序。
最后,“击键”需要包装在“告知应用程序”中,用于“系统事件”。
这里有一个示例,应该可以让您开始:
set textToType to "Peter"
set fieldName to "Account_UserName"
tell application "Google Chrome"
repeat
try
--Chrome needs to have a tab to execute JavaScript in
set myTab to tab 1 of window 1
set fieldNameCheck to execute myTab javascript "nameField=document.getElementById('" & fieldName & "');nameField.name"
if fieldNameCheck is equal to fieldName then
execute myTab javascript "document.getElementById('" & fieldName & "').focus();"
--activate the window so that System Events can type into it
activate myTab
tell application "System Events"
keystroke textToType
keystroke return
end tell
end if
end try
--sleep a second between loop, or AppleScript will eventually lock up the app
delay 1
end repeat
end tell我打开Chrome,开始浏览网页,并开始运行这个脚本;当我导航到测试页面时,它立即检测到我在那里,填写了表格,并将其提交到example.com。
请注意,在实际生活中,您可能会发现使用“JavaScript execute”在javascript中执行整个脚本会更容易,因为您应该能够在那里设置值并提交表单。
https://stackoverflow.com/questions/23261695
复制相似问题