【问题标题】:python 3 import urllib.request modulepython 3 导入 urllib.request 模块
【发布时间】:2014-10-04 16:52:40
【问题描述】:

我正在学习从 URL 中抓取图片,并找到了一个 Q&A here。由于是 Python 3,我将 import urllib 更改为 import urllib.request

urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")

urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg").

这行不通!它说AttributeError: 'module' object has no attribute 'urlretrieve'

然后我将urllib.urlretrieve 更改为def request.urlretrieve 并得到SyntaxError: invalid syntax

我也尝试了def urlretrieve,但它也不起作用。

谁能告诉我怎么弄好?谢谢!

如果网址包含多张图片怎么办?

【问题讨论】:

  • 在 Python 3 中,urllib.request.urlretrieve 应该可以工作。你能发布一些你的代码吗?
  • @hlt,它没有。你需要from urllib import request
  • import urllib.request 然后urllib.request.urlretrieve 在我的 3.4.1 上工作得很好
  • @hlt,我错过了加扰文本的第二部分,我以为 OP 只有一个 import urllib 但我想 urllib.request.urlretrieve 没有与正确的 import statement 结合使用
  • @rain,你今天早上没写对,python没有休息日;)

标签: python-3.x


【解决方案1】:

既然您已经导入了urllib.request 模块,那么您应该将其方法urlretrieve(args) 称为urllib.request.urlretrieve(args) 似乎不是很明显。

  1. 当您输入import <module> 时,您使用<module>.method(args) 调用它的方法(如上述代码中所指定)。

  2. 或者,您可以使用from <module> import * 导入模块,然后使用method(args) 调用其方法。例如 -

    from urllib.request import *

    urlretrieve(args).

  3. 另一种方法是只导入您需要在程序中使用的方法 from <module> import method 然后使用method(args) 调用该方法。例如 -

from urllib.request import urlretrieve 然后调用方法使用

urlretrieve(args).

适用于 Python 3 的 urllib.request 模块有很好的文档记录 here

【讨论】:

    【解决方案2】:

    你需要使用:

    from urllib import request
    request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
    

    你也可以使用:

     import urllib.request
     urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")
    

    【讨论】:

      猜你喜欢
      • 2019-10-07
      • 2012-09-20
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      • 2019-06-30
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多