Find first URL Link on Webpage that matches search input
This AppleScript will search for a keyword in the URL links on a webpage and open the site.
You could use this process to assist in regular web scraping or archiving of content. A tip is to inspect the hyperlink element to see how the link is described as it can be entirely different from the webpage description.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
############################################################# | |
# Title: Find all URL Links on Webage then open link based on a Search value | |
############################################################# | |
#Iain Dunn | |
#https://www.logic2design.com | |
#https://twitter.com/Logic2Design | |
#logic2design@icloud.com | |
############################################# | |
# Script | |
############################################# | |
use AppleScript version "2.4" | |
use framework "Foundation" | |
use scripting additions | |
### Nominated Website option | |
(* | |
set urlLink to "http://www.apple.com" | |
tell application "Safari" | |
set the URL of the front document to urlLink | |
delay 2 | |
set pageText to source of document 1 | |
end tell | |
*) | |
### Safari Front Window option | |
try | |
tell application "Safari" | |
set pageText to source of front document | |
end tell | |
set thelist to my findURLsIn:pageText | |
display dialog "What is the link keyword?" default answer "" | |
set seek to text returned of the result | |
set linkPosition to getPositionOfItemInList(seek, thelist) | |
set firstLink to item linkPosition of thelist | |
tell application "Safari" to set URL of front document to firstLink | |
on error | |
display dialog "The search value was not found" buttons {"OK"} default button "OK" | |
end try | |
################################################################################# | |
# Functions | |
################################################################################# | |
on findURLsIn:theString | |
set anNSString to current application's NSString's stringWithString:theString | |
set theNSDataDetector to current application's NSDataDetector's dataDetectorWithTypes:(current application's NSTextCheckingTypeLink) |error|:(missing value) | |
set theURLsNSArray to theNSDataDetector's matchesInString:theString options:0 range:{location:0, |length|:anNSString's |length|()} | |
return (theURLsNSArray's valueForKeyPath:"URL.absoluteString") as list | |
end findURLsIn: | |
on getPositionOfItemInList(theItem, thelist) | |
repeat with a from 1 to count of thelist | |
if item a of thelist contains theItem then return a | |
end repeat | |
return 0 | |
end getPositionOfItemInList |
Comments
Post a Comment