使用 Node.js 和 Cheerio 抓取公司名称

Scraping Company Names using Node.js and Cheerio

url = http://www.simon.com/mall/anchorage-5th-avenue-mall/stores

上面的 url 列出了特定商场中的所有商店。我想做的是从那个 link 中抓取以获取该商场中所有商店的列表。这是我目前的代码

request(url, function(err, resp, body) {
    if (err) {
        console.log(err);
    } else {

        var $ = cheerio.load(body);

        $('h2.card-secondary-title.name.copy').each(function() {
            var text = $(this).text();
            console.log(text);
        });
    }
})

网页是这种格式

    <html>
      <head>
        <main id="simon" class>
          <section class="directory">
            <div id="root">
              ...
               <div class="directory-grid row">
                 ...
                   <h2 class="card-secondary-title name copy">5th Avenue Deli</h2>

我什至无法从网站上抓取一家商店。使用这种方法,我已经能够从许多其他网站上刮掉,但由于某种原因,这个网站不起作用

您要抓取的内容是通过 ajax 加载的,您将无法使用 cheerio 检索它。

您可以直接复制 ajax 请求,以 JSON 格式检索信息。您正在查看的数据来自此请求:

https://api.simon.com/v1.2/tenant?lw=true&mallId=231

其中包含以下内容:

[
  {
    "brandId": 48,
    "name": "5th Avenue Deli",  // This is the value you want
    /** ... */
    ]
  },
  /* ... */
]

I'm pretty new to javascript so I have no clue what you mean when you say I should replicate the ajax request directly. Could you explain in a little more detail?

复制 Ajax 调用的一种简单方法是检查 chrome 开发人员工具 (F12)

上的请求

然后前往 network tab > XHR filter > locate the request > right click > copy > copy as cURL

然后从 curl 到你想在服务器端使用的任何库,转换起来非常容易。