How to download an image using Selenium (any version)?

前端 未结 13 1589
夕颜
夕颜 2020-11-29 04:11

I was wondering, how can one use selenium/webdriver to download an image for a page. Assuming that the user session is required to download the image hence having pure URL i

13条回答
  •  星月不相逢
    2020-11-29 04:47

    here is a javascript solution. it's a tad silly -- and i'm weary of hitting the source image's server with too many requests. can someone tell me if the fetch() accesses the browser's cache? i don't want to spam the source server.

    it appends a FileReader() to the window, fetches and converts the image to base64 and tags that string onto the window.

    the driver can then return that window variable.

    export async function scrapePic(driver) {
    try {
    console.log("waiting for that profile piccah")
    console.log(driver)
    
    let rootEl = await driver.findElement(By.css('.your-root-element'));
    let imgEl = await rootEl.findElement(By.css('img'))
    await driver.wait(until.elementIsVisible(imgEl, 10000));
    console.log('profile piccah found')
    let img = await imgEl.getAttribute('src')
    //attach reader to driver window
    await driver.executeScript(`window.myFileReader = new FileReader();`)
    await driver.executeScript(`
      window.myFileReader.onloadend = function() {
        window['profileImage'] = this.result
      }
      fetch( arguments[0] ).then( res => res.blob() ).then( blob => window.electronFileReader.readAsDataURL(blob) )
      `, img)
    await driver.sleep(5000)
    let img64 = await driver.executeScript(`return window.profileImage`)
    console.log(img64)
    
    
    } catch (e) {
    console.log(e)
    } finally {
    return img64
      }
    }
    

提交回复
热议问题