【问题标题】:Image URL Is Not Opening with Puppeteer图像 URL 未使用 Puppeteer 打开
【发布时间】:2021-07-08 16:28:51
【问题描述】:

我需要能够打开并截取网页抓取项目的图片网址。我的脚本在给定初始页面 URL 时工作正常,但是在检索到所需的图像 URL 后,它不起作用。

这是主脚本中的函数:

function ImageFetcher(pageURL, partName, urlHostName, selector) {
  return new Promise( async (resolve, reject) => {
  try {        
      const browser = await puppeteer.launch({
        headless: false,
      });  
      const page = await browser.newPage();      
      await page.goto(pageURL);

      let imageHref = await page.evaluate((sel) => {
        return document.querySelector(sel).getAttribute('src').replace('//', 'https://');
    }, selector)
      console.log(imageHref);   

      await page.close();

      await page.goto(imageHref);
      await page.waitForSelector("body > img");
      const image = await page.$("body > img");
      await image.screenshot({path: `./image-test/${partName}.png`});

      await page.close();
      await browser.close();   

      console.log(`${urlHostName.host} Image Captured`); 
      return resolve();
    } catch(e) {console.log(`Error ${urlHostName.host}! Part Name: ${partName}`)};
  });
}

var index = 0; 
var array = json.Part;
async function start() {
  for (let index = 0; index < 1; index++) {
    const element = array[index];
    try {
        await urlSorter(element);
    } catch(e) {console.log(`URL Sorter Error, Part Name: ${partName} ${urlHostName.host}`)};
  }
} start();

这是一个关于这个问题的更孤立的测试(这也不起作用,打开的页面是空白的)

const puppeteer = require('puppeteer');

pageURL = "https://static.grainger.com/rp/s/is/image/Grainger/1RVB9_AS01?hei=536&wid=536";


function ImageFinder(pageURL) {
    return new Promise( async (resolve, reject) => {
      try {
        const browser = await puppeteer.launch({
          headless: false,
        });  
        const page = await browser.newPage();  
        await page.goto(pageURL);
        
        await page.close();
        await browser.close();

  
      } catch(e) {console.log(`ERR`)}
    })
  }

  ImageFinder(pageURL);

This is the result of both versions of the above code

However, if manually paste the URL in to the browser the image displays

【问题讨论】:

    标签: node.js web-scraping puppeteer


    【解决方案1】:

    您的网址缺少协议部分。在浏览器地址栏中手动粘贴时会自动添加,但需要通过 puppeteer 明确指定。

    那就试试吧:

    pageURL = "http://static.grainger.com/rp/s/is/image/Grainger/1RVB9_AS01?hei=536&wid=536";
    

    【讨论】:

    • 哇,我不敢相信我错过了,感谢您指出。我相信我做出了正确的更改来解决添加协议的问题。但是,它在运行时仍会打开 about:blank 页面。我将编辑代码 sn-p 以显示更改。
    • 没关系,问题出在函数的其他地方。不过,新 URL 在隔离测试示例中有效,谢谢!!
    猜你喜欢
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多