Python selenium upload a file using windows browser

前端 未结 2 1626
傲寒
傲寒 2021-01-25 22:37

I am working on a browser automation project in Python using selenium. I am trying to upload a picture to a page. I login, go to the page, and click the upload button. After cli

2条回答
  •  独厮守ぢ
    2021-01-25 23:17

    Here's an idea for doing a file upload without popping the chooser:

    filename = 'x.jpg'
    with open(filename, "rb") as file:
      content = base64.b64encode(file.read()).decode('utf8')
    mimeType = "image/jpeg"
    selector = "input[type=file]"
    
    driver.execute_async_script("""
      const [filename, content, mimeType, selector, cb] = arguments
    
      const dt = new DataTransfer()
      const response = await fetch(`--data:${mimeType};base64,${content}`)
      const file = new File([await response.blob()], filename)
      dt.items.add(file)
    
      const element = document.querySelector(selector)
      element.files = dt.files
      element.dispatchEvent(new Event('input', { bubbles: true }))
      cb()
    """, filename, content, mimeType, selector)
    
    driver.find_element_by_css_selector('input[type=submit]').click()
    

    Also you might want to think about switching to Puppeteer for things like this because Selenium is not likely to ever have a good implementation of this.

提交回复
热议问题