【问题标题】:How to authenticate and download an image from a website?如何从网站验证和下载图像?
【发布时间】:2017-04-27 14:09:07
【问题描述】:

我见过许多管理身份验证和从网站下载图像的解决方案,但我有点迷失在所有这些库中:

  • urllib
  • urllib2
  • pycurl
  • 请求
  • 其他我不明白的黑暗解决方案...

基本上,我想从需要身份验证的网站检索图像。在 python-2.7 中最简单的方法是什么?

谢谢。

【问题讨论】:

    标签: python python-2.7 python-requests urllib pycurl


    【解决方案1】:

    您可以查看请求doc。例如,如果您需要基本的 HTTP 身份验证:

    requests.get('http://example.com/image.png', auth=HTTPBasicAuth('user', 'pass'))
    

    【讨论】:

      【解决方案2】:

      我终于设法只用requests 做到了。

      import requests
      
      url_login = ''
      url_image = ''
      
      username = ''
      password = ''
      
      # Start a session so we can have persistant cookies
      session = requests.session()
      
      # This is the form data that the page sends when logging in
      login_data = {
          'login': username,
          'password': password,
          'submit': 'Login'
      }
      
      # Authenticate
      r = session.post(url_login, data=login_data)
      
      # Download image
      with open('output.png', 'wb') as handle:
          response = session.get(url_image, stream=True)
      
          if not response.ok:
              print "Something went wrong"
              return False
      
          for block in response.iter_content(1024):
              handle.write(block)
      
          handle.close()
      

      【讨论】:

        猜你喜欢
        • 2018-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-05
        相关资源
        最近更新 更多