Applescript не вводится, чтобы преуспеть. Должно быть просто?
Это действительно просто. Вот кусочки моего кода, который выполняет действие. Проблема в том, что информация, которую я пытаюсь получить с сайта, не вводится в документ Excel.
<div class="book-price">
$53.25 </div> == $0
Вот как выглядит код на сайте. Все, что я хочу, это введенные $53.25.
set i to 2
repeat 725 times
activate application "Microsoft Excel"
tell application "Microsoft Excel"
end tell
tell application "System Events"
keystroke "c" using command down
delay 1
end tell
activate application "Google Chrome"
tell application "System Events"
keystroke "t" using command down
delay 1
keystroke "https://bookscouter.com/prices.php?isbn="
keystroke "v" using command down
keystroke "&searchbutton=Sell"
delay 1
keystroke return
delay 10
end tell
set theText to getInputByClass("book-prices", 0)
tell application "Microsoft Excel"
set value of cell ("k" & (i as string)) to theText
end tell
set i to i + 1
tell application "System Events"
keystroke "w" using command down
end tell
end repeat
to getInputByClass(theClass, num)
tell application "Google Chrome"
tell active tab of window 1
set input to execute javascript "document.getElementsByClassName('" & theClass & "')[" & num & "].innerHTML;"
end tell
end tell
return input
Я думаю, что это что-то очень основное, что я не вижу. Информация, вставляемая изначально, isbns. Например 9781464139055.
Спасибо!
1 ответ
Это тривиальный пример, потому что значение одинаково в каждом цикле, но оно работает. Это в основном код, который вы используете (единственное отличие - реализация цикла и входной текст).
on run
set theText to "Sample Input"
repeat with i from 2 to 300
tell application "Microsoft Excel"
set value of cell ("k" & (i as string)) to theText
end tell
end repeat
end run
Единственное, что я могу догадаться, это то, что ваш вводимый текст не соответствует вашим ожиданиям. Когда вы просматриваете свой код, кажется, что вы пытались создать собственную функцию под названием getInputByClass
? Не уверен, что это просто опечатка в вашем сообщении или нет, но эта функция сформирована неправильно, что может быть вашей проблемой.
Вот небольшая переделка вашего кода...
on run
repeat with i from 2 to 725
tell application "Microsoft Excel" to activate -- these activate lines may not be necessary
tell application "System Events"
keystroke "c" using command down
delay 1
end tell
tell application "Google Chrome" to activate -- these activate lines may not be necessary
tell application "System Events"
keystroke "t" using command down
delay 1
keystroke "https://bookscouter.com/prices.php?isbn="
keystroke "v" using command down
keystroke "&searchbutton=Sell"
delay 1
keystroke return
delay 10
end tell
set theText to getInputByClass("book-prices", 0)
tell application "Microsoft Excel"
set value of cell ("k" & (i as string)) to theText
end tell
tell application "System Events"
keystroke "w" using command down
end tell
end repeat
end run
on getInputByClass(theClass, num)
try
tell application "Google Chrome"
tell active tab of window 1
set input to execute javascript "document.getElementsByClassName('" & theClass & "')[" & num & "].innerHTML;"
end tell
end tell
return input
on error
return "Error getting input"
end try
end getInputByClass
В качестве еще одного примечания, я думаю, что вы могли бы внести другие улучшения в этот скрипт. Вы не должны использовать keystrokes
чтобы получить контент из Excel и чтобы Chrome открыл новую вкладку и перешел на страницу. Это можно сделать напрямую с помощью сценариев Excel и Chrome. Если вы можете избежать использования System Events
а также keystroke
Ваш сценарий будет более стабильным.
Например, вместо того, чтобы пытаться скопировать содержимое из ячейки, выбранной в Excel, вы можете использовать это.
tell application "Microsoft Excel" to set theText to string value of selection
Затем вы можете использовать это, чтобы создать свой окончательный URL-адрес, как это...
set MyURL to "https://bookscouter.com/prices.php?isbn=" & theText & "&searchbutton=Sell"
ОБНОВИТЬ!!!
У меня было немного больше времени для просмотра вашего кода, и ваша проблема в том, что ваш javascript не находит этот класс на странице, он не существует.
Я думаю, у вас есть еще несколько вещей для работы с вашим кодом, потому что кажется, что вы будете продолжать открывать и закрывать одну и ту же страницу, что, очевидно, является пустой тратой энергии. Кроме того, кажется, что вы постоянно нацеливаетесь на одни и те же данные для своего листа Excel, как при захвате контента, вы не увеличиваете число при вызове функции. В любом случае обновленный код, приведенный ниже, похож на ваш код, но вычищен и делает то, что, по моему мнению, вы пытаетесь сделать. Я переместил открытие URL за пределы цикла повторения, что значительно увеличит скорость ваших действий.
Более глубокая доработка вашего кода
on run
tell application "Microsoft Excel" to set theText to string value of selection
set MyURL to "https://bookscouter.com/prices.php?isbn=" & theText & "&searchbutton=Sell"
tell application "Google Chrome" to open location MyURL
do shell script "sleep 1" -- give the tab time to load
tell application "Google Chrome" to set newTab to active tab of window 1
do shell script "sleep 3" -- give the page time to load
repeat with i from 2 to 725
set theText to getInputByClass("book-price-normal", i - 2)
if theText as text is not "Missing Value" then
tell application "Microsoft Excel" to set value of cell ("k" & (i as string)) to theText
else
exit repeat
end if
end repeat
tell application "Google Chrome" to close newTab
end run
on getInputByClass(theClass, num)
try
tell application "Google Chrome"
tell active tab of window 1
set input to execute javascript "document.getElementsByClassName('" & theClass & "')[" & num & "].innerHTML;"
end tell
end tell
return input
on error
return "Error getting input"
end try
end getInputByClass