Server-side jquery
Asked Answered
I

2

4

Say I have a script written in perl or python. What's the easiest way to write a function that would use jquery selectors on strings as part of it? i.e. to be able to do:

jquery_selector('table.new#element', text)

where jquery_selector is a function that runs a jquery selector on the html string stored in text. Even if it was just limited to returning strings (not full jquery objects), it would still be really useful. i.e. if you were required to give a javascript function as a callback which would render the results to something comprehensible in the scripting language:

jquery_selector('table.new#element, text, 'function(e){return e.val()}')

And it would return the results of the callback as a list.

I realize that there are dom libraries for most languages, but jquery is so much better than most of them.

I am not asking about native libraries which have a syntax like jquery. I guess what would be needed is an API to a browser which jquery would run on? Or is this what node.js does?

Interference answered 29/6, 2012 at 2:9 Comment(1)
For meteor 1.0, and slightly different approach https://mcmap.net/q/823873/-require-jquery-in-meteor-server-sideRogers
T
4

if i understand your question correctly you want is something like phantom.js. PhantomJS is a headless WebKit with JavaScript API. you can inject jquery into it and use all the jquery selectors to manipulate the dom. you can make it work like a standalone server aswell.

Tearjerker answered 29/6, 2012 at 2:21 Comment(2)
Knowing they're called headless browsers is half the battle. There's also Zombie.js for node.js.Gatehouse
@Jared Farrish zombie.js is a testing frame work but there is a phantom node module.github.com/sgentle/phantomjs-nodeTearjerker
O
0

I am confused as you have tagged the question with "node.js" though you refer to Python or Perl in your question. Running node.js and/or phantom.js just to run a selector on an HTML DOM sounds quite heavyweight to me, and as always introducing whole chains of dependencies should be considered carefully in real-world projects.

So for Python I would suggest running a combination of BeautifulSoup and soupselect, as mentioned in this answer. You can then do things like:

from BeautifulSoup import BeautifulSoup as Soup
from soupselect import select
import urllib

soup = Soup(urllib.urlopen('http://slashdot.org/'))
select(soup, 'div.title h3')

Note that soupselect seems to implement only a subset of jquery's CSS3 selectors, so for things like e.g. sibling selectors or pseudo-classes it may not work. In this case I would advise to consider porting the relevant part of the project to node.js were you can run Sizzle (jQuery's selector engine) or cheerio standalone in a somewhat lightweight environment.

Oys answered 16/8, 2014 at 9:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.