0

I have this AppleScript

tell application "Safari"
    open location "https://www.facebook.com/friends/list"
    delay 5
    set selectedText to do JavaScript "document.evaluate('//div/div[1]/div/div[3]/div/div/div/div[1]/div[1]/div[1]/div/div/div[1]/div[2]/div/div/a/@href', document, null, 0, null)" in front document
end tell

The intention is to get a list of all URLs to my friends profile pages (the XPath points toward a href-attribute with that link) but the result is empty. I am looking for a list, array or something like that with URLs ("http://facebook.com/name1", "http://facebook.com/name2" or similar) as return value.

I have also tried pointing at a specific friend (and then loop over the list with friends), but with the same, empty result.

2 questions:

  1. Can I get an array, list or similar with values from a Javascript executed XPath using AppleScript and Safari? Or do I need to find the number of items first and the create a loop that fetches one at a time and insert the fetched value in an AppleScript array?

  2. What is wrong with my XPath? Even if I execute it in the browser console I think something is broken with my expression (or the arguments to document.evalutate, but I have mostly used the default values recommended in Mozilla's documentation)

I have read several related questions, but without finding a solution, e.g.,:

Getting attribute using XPath

How to get attribute value using XPath in Java?


If I modifid the XPath slightly, to document.evaluate('string(//div/div[1]/div/div[3]/div/div/div/div[1]/div[1]/div[1]/div/div/div[1]/div[2]/div/div[6]/a/@href)', document, null, 0, null) it worked in the console (but only returns one value at the time).

But when running the AppleScript with this modified version of the XPath still doesn't return anything.

d-b
  • 695
  • 3
  • 14
  • 43
  • In the browser console you can use `$x('//div/div[1]/div/div[3]/div/div/div/div[1]/div[1]/div[1]/div/div/div[1]/div[2]/div/div/a/@href')` to get an array of `href` attribute nodes. – Martin Honnen Mar 19 '23 at 13:29
  • 1
    You can try e.g. `var links = []; var xpathResult = document.evaluate('//div/div[1]/div/div[3]/div/div/div/div[1]/div[1]/div[1]/div/div/div[1]/div[2]/div/div/a/@href', document, null); var href = null; while ((href = xpathResult.iterateNext()) != null) { links.push(href.value); } ; links` as the complete JavaScript to pass to Safari to return an array of strings with the link URLs. – Martin Honnen Mar 19 '23 at 13:47

0 Answers0