Reputation: 1109
Trying to return a list of users in a chat room. The HTML looks like:
<div class="users-list" style="height: 475px; display: block;">
That expands to this:
<div class="text" data-nick style="float:right">...</div>
<div class="text" data-nick="user1">...</div>
<div class="text" data-nick="user2">...</div>
<div class="text" data-nick="user3">...</div>
<div class="text" data-nick="user4">...</div>
Using the javascript console in Google Chrome, I do:
document.body.querySelector("div.users-list")
Which returns the original unexpanded HTML:
<div class="users-list" style="height: 475px; display: block;">
There is a drop down arrow to expand this in the javascript console which returns the user list:
<div class="text" data-nick style="float:right">...</div>
<div class="text" data-nick="user1">...</div>
<div class="text" data-nick="user2">...</div>
<div class="text" data-nick="user3">...</div>
<div class="text" data-nick="user4">...</div>
What I'd like to do is write the list of users to a text file. I tried doing this in Bash with osascript
:
osascript -e \
'tell application "Google_Chrome"
tell window 1
tell active tab
execute javascript "document.body.querySelector(\"div.users-list\")"
end tell
end tell
end tell'
But when I run this in my terminal it returns a blank line. When I run this as AppleScript in Script Editor, it only returns {}
How can use the javascript "document.body.querySelector(\"div.users-list\")"
in AppleScript / osascript to return the same expanded user list that is returned using the javascript console in Google Chrome?
Upvotes: 0
Views: 521
Reputation: 15327
Element.querySelector doesn't return a string (HTML or otherwise); it returns an Element object. Chrome renders this in the console with text, but AppleScript/osascript might render it differently, or not at all.
You might want to consider using innerHTML
, which returns the HTML of the contents as a string:
execute javascript "document.body.querySelector(\"div.users-list\").innerHTML"
Since there is an appropriate rendering for an array of strings, we can map each of the children of the div.users-list
to some string, using the Array.prototype.map
method:
execute javascript "[...document.querySelector(\"div.users-list\").children].map(x => x.outerHTML)"
(This also makes use of spread syntax and arrow functions:
Of course, you can also extract information from each child div within map and return that information. The following uses dataset
to read HTML5 data-*
attributes:
execute javascript "[...document.querySelector(\"div.users-list\").children].map(x => x.dataset.nick)"
and will output:
user1, user2, user3, user4
Upvotes: 1