【问题标题】:I can't practice data scraping using javascript我无法使用 javascript 练习数据抓取
【发布时间】:2020-11-17 13:45:27
【问题描述】:

我正在尝试为我们的项目练习数据抓取,如果我输入 node scrapers.js,我可以成功查看数据。但是,当我将其加载到 livecount.html 文件中时,会显示错误,并且无法显示从数据抓取中收集的数据。

错误是: “由于 MIME 类型(“text/html”)不匹配(X-Content-Type-Options: nosniff)而被阻止”

这是来自 html 文件的代码

<html lang="en">
<head>
</head>
<body>
    Total cases: 
    <span id="totalCases"></span> <br>
    Recovered cases:
    <span id="recovered"></span> <br>
    <script src="scrapers.js" type="text/html">
    </script>
</body> </html>

这是来自 scrapers.js 的代码

const puppeteer = require('puppeteer');

    async function scrapeProduct(url){
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto(url);
    
        const [el] = await page.$x('//*[@id="yDmH0d"]/c-wiz/div/div[2]/div[2]/div[4]/div/div/div[2]/div/div[1]/table/tbody/tr[2]/td[1]');
        const txt = await el.getProperty('textContent');
        const rawTxt = await txt.jsonValue();
    
        console.log(rawTxt);
        
        const [el2] = await page.$x('//*[@id="yDmH0d"]/c-wiz/div/div[2]/div[2]/div[4]/div/div/div[1]/div[1]/div/div/div[2]/div[2]');
        const txt2 = await el2.getProperty('textContent');
        const recovered = await txt2.jsonValue(); 
        
        console.log(recovered);
        browser.close();
        document.write("total cases: " + rawTxt + "\n" + "recovered: " + recovered);
    }
    
    scrapeProduct('https://news.google.com/covid19/map?hl=en-PH&gl=PH&ceid=PH%3Aen&mid=%2Fm%2F05v8c');

我只是对这些东西不熟悉,所以我真的不知道它们是如何工作的,只是为我们的网站项目练习一些东西,我想从另一个网站向我们的网站显示数据。任何意见都会有所帮助!谢谢

【问题讨论】:

    标签: javascript web screen-scraping


    【解决方案1】:

    抓取通常在服务器上完成,而不是在浏览器上。我建议更改您的项目结构如下。

    [原样] html > js > puppeteer > ?
    [To-be] html > js > ajax 调用你的服务器[nodejs] -> 从服务器获取数据:)

    【讨论】:

      猜你喜欢
      • 2017-07-12
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 2018-06-10
      相关资源
      最近更新 更多