【问题标题】:opening a url with urllib in python 3在 python 3 中使用 urllib 打开一个 url
【发布时间】:2016-05-01 10:59:50
【问题描述】:

我正在尝试从阳光基金会打开此 API 的 URL,并以 json 格式从页面返回数据。这是我生成的代码,减去 myapikey 周围的括号。

import urllib.request.urlopen
import json

urllib.request.urlopen("https://sunlightlabs.github.io/congress/legislators?api_key='(myapikey)")

我得到了这个错误

Traceback (most recent call last):
  File "<input>", line 1, in <module>
ImportError: No module named request.urlopen

我做错了什么?我研究了https://docs.python.org/3/library/urllib.request.html 仍然没有进展

【问题讨论】:

    标签: python python-3.x url urllib


    【解决方案1】:

    您需要使用from urllib.request import urlopen,另外我建议您在打开连接时使用with 语句。

    from urllib.request import urlopen
    
    with urlopen("https://sunlightlabs.github.io/congress/legislators?api_key='(myapikey)") as conn:
        # dosomething
    

    【讨论】:

    • 也许我不完全理解这个概念,但我对 python 还很陌生,但是一旦我输入你给出的代码,我就会得到第 4 行的缩进错误(后面的空行是 conn:) 是否还有其他我应该使用的代码来遵循这个?我不希望你为我编写我的程序,但任何资源将不胜感激。或创。信息
    • @BradleyD.Freeman-Bain:如果没有以下块,您将无法拥有 with-statement。为了避免SyntaxError,添加任何代码,即使只是pass 也可以。
    • @BradleyD.Freeman-Bain "with" 语句将urlopen 的返回值分配给conn,并允许您在其正下方的本地范围内对其进行操作。一旦你逃脱,它就会被删除。
    【解决方案2】:

    在 Python 3 中你可以这样实现:

    import urllib.request
    u = urllib.request.urlopen("xxxx")#The url you want to open
    

    注意: 有的IDE可以直接import urllib(Spyder),有的需要import urllib.request(PyCharm)。

    那是因为你有时需要显式地导入你想要的部分,所以当你只想要它的一小部分时,模块不需要加载所有东西。

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:
      from urllib.request import urlopen
      from bs4 import BeautifulSoup
      
      wiki = "https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India"
      
      page = urlopen(wiki)
      soup =  BeautifulSoup(page, "html.parser" ).encode('UTF-8')
      
      print (soup)
      

      【讨论】:

      • 嗨,如果您发布代码,您可以将其格式化为代码,以便保留空格,就像您输入它们一样,并完成语法突出显示。为此,请选择您的代码并单击编辑器中的大括号,或者将代码缩进四个空格。我为你做了这个答案。如果你能写一点来解释你的代码,那就太好了。
      【解决方案4】:

      urllib.request 是一个模块,而urlopen 是一个函数。 查看此链接,它可以帮助您消除疑虑。 https://docs.python.org/3.0/library/urllib.request.html

      【讨论】:

      • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效
      【解决方案5】:

      问题在于您的模块导入。 在 Python3.x 中有多种方法可以做到这一点:

      from urllib.request import urlopen
      urlopen('example.com/***')
      

      from urllib import request
      request.urlopen('example.com/***')
      

      import urllib
      urllib.request.urlopen('example.com/***')
      

      此外,您还可以命名要导入的模块:

      import urllib.request as req  ## or whatever you want
      req.urlopen('example.com/***')
      

      您可以使用您喜欢的那个,但请注意您使用的模块和包的顺序。

      【讨论】:

        猜你喜欢
        • 2013-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 2015-10-16
        • 1970-01-01
        • 2017-02-06
        • 1970-01-01
        相关资源
        最近更新 更多