Michael
Michael

Reputation: 16142

Cheerio: SyntaxError: Malformed attribute selector: object global?

Here is my code:

var request = require('request'),
    cheerio = require('cheerio'),
    async = require('async');

function updateCars(){

    function getReviews(body){
        var $ = cheerio.load(body);
        var year = $(this).find(".field-item").text();
    }

    async.series([
        ....
        function(callback) {
            request(site+path, function(err, resp, body){
                if(!err && resp.statusCode == 200){
                    var $ = cheerio.load(body);
                    $(".views-row").each(getReviews(body));
                }
            });
        }
    ]);
}

When I run it in the node console, I get the follwing error:

SyntaxError: Malformed attribute selector: object global]

How can I fix that?

Upvotes: 4

Views: 4708

Answers (1)

wahwahwah
wahwahwah

Reputation: 3177

The error...

SyntaxError: Malformed attribute selector: object global]

Is actually spot on. Since there's only a snippet of the offending code posted here, it's not entirely clear where this is happening, but it's definitely a clerical error in an attribute selector - and most likely it's this...

Answer:

$('div[id^=foo_bar'); // <-- missing the closing ]

The above example is an error you normally (or whoever coded the site you are scraping) wouldn't notice because jQuery normally quietly handles this mistake...

Proof jQuery Handles It:

var fooBars = $('a[id^="foo_bar"'); //<-- missing closing ]
$('#results').append("See... jQuery don't care about your closing ']' -" + fooBars.length)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="foo_bar_1">1</a>
<a id="foo_bar_2">2</a>
<a id="foo_bar_3">3</a>
<a id="foo_bim_4">4</a>
<a id="foo_bar_5">5</a>

<div id="results"></div>

Explanation:

The error is actually Sizzle yelling at you, from somewhere beneath cheerio. While jQuery is utilizing the pure javascript implementation...

var fooBar = document.querySelectorAll('a[id="foo_bar"'); // <-- missing
alert(fooBar.length); // works!

Cheerio is using Sizzle, which does not like the "malformed" attribute (used to be a problem in IE 7-9 as well)...

Like jQuery, [Cheerios] primary method for selecting elements in the document, but unlike jQuery it's built on top of the CSSSelect library, which implements most of the Sizzle selectors.

Upvotes: 1

Related Questions