【问题标题】:I'm requesting html content from a site with axios in JS but the website is blocking my request我正在使用 JS 中的 axios 从网站请求 html 内容,但该网站阻止了我的请求
【发布时间】:2020-04-08 00:47:21
【问题描述】:

我希望我的脚本从网站中提取 html 数据,但它返回的页面显示它知道我的脚本是机器人,并给它一个“我不是机器人”测试以通过。

它不是返回站点的内容,而是返回一个页面,其中部分内容... "

在您浏览时,您的浏览器\n 的某些内容让我们认为您是机器人。"

我的代码是……

const axios = require('axios');

const url = "https://www.bhgre.com/Better-Homes-and-Gardens-Real-Estate-Blu-Realty-49231c/Brady-Johnson-7469865a";
axios(url, {headers: {
  'Mozilla': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.3 Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/43.4.0',
}})
.then(response => {
  const html = response.data;
  console.log(html)
})
.catch(console.error);

我已经尝试了几个不同的标题,但没有欺骗网站认为我的脚本是人类的。这是在 NodeJS 中。

也许这对我的问题有影响,也可能没有,但这段代码有望在我正在构建的 React 网站的后端存在。我不是想把这个网站当作一次性的。我希望我的网站从 this 网站中读取一些内容,而不是在我的网站发生变化时手动更新我的网站。

【问题讨论】:

    标签: node.js web-scraping request axios


    【解决方案1】:

    使用 axios 或 curl 访问每个站点是不可能的。包括 CORS 在内的各种检查可以防止某人通过浏览器以外的客户端直接访问网站。

    您可以使用 phantom (https://www.npmjs.com/package/phantom) 实现相同的目的。这通常由爬虫使用,如果您担心其他站点可能会阻止您重复访问,您可以在发出请求之前使用随机间隔。如果您需要从返回的 HTML 页面中读取内容,可以使用cheerio (https://www.npmjs.com/package/cheerio)。

    希望对你有帮助。

    以下是我为您的 URL 尝试和工作的代码:

    const phantom = require('phantom');
    
    (async () => {
        const url = "https://www.bhgre.com/Better-Homes-and-Gardens-Real-Estate-Blu-Realty-49231c/Brady-Johnson-7469865a";
        const instance = await phantom.create(['--ignore-ssl-errors=yes', '--load-images=no']);
        const page = await instance.createPage();
        const status = await page.open(url);
    
        if (status !== 'success') {
          console.error(status);
          await instance.exit();
          return;
        }
    
        const content = await page.property('content');
        await instance.exit();
        console.log(content);
    })();
    

    【讨论】:

    • 感谢您的回答。关于如何使用您链接的 phantonJS 在操作中尝试做的事情的文档方式并不多。我得到UnhandledPromiseRejectionWarning: Error: Required option "capabilities" is missing 出于某种原因在这里使用“使用webdriver 运行”示例github.com/Medium/phantomjs
    • 换句话说:如果您使用了您链接的 npm 包来执行我在 OP 中尝试执行的操作,如果您将其复制并粘贴到您的答案中,我将不胜感激。
    • 好的,请让我将其添加到我的答案中。
    • 请查看我添加到答案中的代码示例。我试过了,它奏效了。我在包的链接中犯了一个错误。不是phantomjs,而是phantom。谢谢。
    • "不是 phantomjs 而是 phantom。"有趣的是,我在离开我的 cmets 几个小时后发现了 phantom 包裹。谢谢!
    猜你喜欢
    • 2019-07-14
    • 1970-01-01
    • 2023-01-29
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多