I’m trying to input text into a search bar and then click the search button. It’s input the text into the search bar but I’m having trouble getting it to click the search button. Here’s what I have:
set a_number to "123456"
--Putting number into search bar
tell application "Safari" -- tells AppleScript to use Safari
activate
do JavaScript "document.getElementsByName('keyword')[0].value ='" & a_number & "';" in document 1
end tell
--Clicking search button to start search
tell application "Safari"
do JavaScript "document.getElementsByTagName('button')[0].click();" in document 1
end tell
Here’s the HTML:
<div id="headerSearchBar" class="relative flex-adapt hide-tablet">
<form action="/s/" role="search" class="search-wrapper flex flex-adapt relative">
<div class="header-search" style="z-index: 4;">
<label id="headerSearchBarLabel" for="searchInput_1706200841199" class="hide-aria"></label>
<input type="text" id="searchInput_1706200841199" name="keyword" placeholder="Search" maxlength="150" autocomplete="off" aria-invalid="true" aria-required="true" aria-describedby="bb8e69eb-619c-42f9-bc31-5332d76ad590">
<button type="submit" class="absolute"><span aria-hidden="true" class="searchbar-search-icon icon icon-search"></span> <span class="hide-aria">Search</span></button>
</div>
</form>
</div>
Years ago, that code did click the search button on the website that’s now being stubborn. If I changed the number of the button to [1], [2], [3], etc. instead of [0], it was clicking the cart and other buttons. It just didn’t want to click the search button.
I found a different approach that worked. The product page URL is something like “https://www.websitename/products/123456-short-product-description-here”. If I have it dynamically enter “https://www.websitename/products/123456”, it will automatically redirect to “https://www.websitename/products/123456-short-product-description-here”
--Setting a_number variable to a number for testing purposes
--In the larger code it pulls the number from an image filename
set a_number to "123456"
--Going to the web page
go_to_web_page(("https://www.websitename/products/" & a_number as string))
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
--FUNCTIONS
---------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
--Opening a Web Page
to go_to_web_page(web_page)
tell application "Safari"
activate
set URL of document 1 to web_page
end tell
end go_to_web_page