【问题标题】:Scrape background-image with puppeteer用 puppeteer 抓取背景图像
【发布时间】:2020-06-06 17:19:09
【问题描述】:

谁能解释我如何使用 Puppeteer 从网页中抓取背景图片?图像在图像背景类中,但其中没有存储任何内容。 jpg URL 在

element.style { 背景图片:url('https://xxxxx.jpg')

如何抓取 URL 'https://xxxxx.jpg'?

谢谢

【问题讨论】:

  • 你能提供给我们你到目前为止所尝试的吗?

标签: web-scraping background-image puppeteer


【解决方案1】:

我对正则表达式了解不多,但通过这种方式完成了。

 const backgroundImage = await page.evaluate(el => window.getComputedStyle(el).backgroundImage, await page.$('.home-masthead'))

 const backgroundImageUrl = backgroundImage.substring(5,backgroundImage.length-2);

【讨论】:

    【解决方案2】:

    您将需要window.getComputedStyle 来检索元素的 CSS 属性。

    示例:

    您可以在 Chrome DevTools 中测试一下如何达到预期的效果。

    getComputedStyle($('.home-masthead')).backgroundImage

    Get the right property with chrome dev tools

    那么 puppeteer 脚本可以是这样的:

    const puppeteer = require('puppeteer')
    
    async function getBackgroundImage() {
      try {
        const browser = await puppeteer.launch({ headless: false })
        const page = await browser.newPage()
        await page.goto('https://developer.mozilla.org/en-US/')
    
        const backgroundImage = await page.evaluate(el => window.getComputedStyle(el).backgroundImage, await page.$('.home-masthead'))
        console.log(backgroundImage)
    
        await browser.close()
      } catch (e) {
        console.error(e)
      }
    }
    getBackgroundImage()
    
    

    结果:

    url("https://developer.mozilla.org/static/img/home-masthead-background.37a14f03abee.svg")

    在这之后你只需要清理一下字符串,我会用正则表达式match()来做,这样你就可以得到两个模式之间的内容,例如:

    const backgroundImageCleaned = backgroundImage.match(/url\("(.*)"/)[1] 
    

    当然,在您的情况下,子字符串方法以及此 CSS 属性将始终具有相同的格式。

    【讨论】:

    • 谢谢大卫,对不起,我是新手,你如何用正则表达式删除 URL 和“”()?我认为 replace() 不会取出 URL 字符串,我不想删除字母 URL,因为 href 中可能有一些。
    • 通过在match 中使用它,您可以获得两种模式之间的内容,例如:const backgroundImageCleaned = backgroundImage.match(/url\("(.*)"/)[1] 当然,在您的情况下,子字符串方法以及此 CSS 属性将具有相同的格式一直都是。
    猜你喜欢
    • 2019-11-07
    • 2023-03-16
    • 2022-07-21
    • 1970-01-01
    • 2013-07-15
    • 2016-11-27
    • 2020-06-08
    • 2017-01-14
    • 1970-01-01
    相关资源
    最近更新 更多