【问题标题】:urllib is not defined - cannot import "urllib.request import urlopen"urllib 未定义 - 无法导入“urllib.request import urlopen”
【发布时间】:2021-02-12 08:22:25
【问题描述】:

我收到一个错误“NameError: name 'urllib' is not defined”。但是我正在尝试导入 urlopen 但是它是灰色的(第二行代码在 Intellij 中是灰色的,因为它认为它没有必要)。我是否错误地导入它?或者我的代码中是否有其他原因导致错误?

请检查我的代码并提供帮助。

from html.parser import HTMLParser
from urllib.request import urlopen


class ContentParser(HTMLParser):

    def __init__(self):
        HTMLParser.__init__(self)
        self.tagList = []
        self.wordDictionary = {}

    def handle_starttag(self, tag, attrs):
        self.tagList.append(tag)

    def handle_endtag(self, tag):
        self.tagList.pop()

    def handle_data(self, data):
        if len(self.tagList) > 0 and (self.tagList[-1]) not in ["script"]:
            self.AddContents(data)

    def AddContents(self, data):
        data = self.RemoveSpecialChar(data)
        contents = data.split()
        for word in contents:
            word = word.decode("utf-8")
            if word in self.wordDictionary:
                self.wordDictionary[word] += 1
            else:
                self.wordDitionary[word] = 1

    def RemoveSpecialChar(self, data):
        data = str.encode(data)
        ret = data
        for char in data:
            if not ((char >= ord("a") and char <= ord("z")) or (char >= ord("A"))):
                if char != ord(""):
                    ret = ret.replace(bytes(chr(char), "utf-8"), b"")
        return ret

    def PrintTopUsedWords(self, count):
        sortedDic = sorted(self.wordDictionary.items(), key=lambda x: x[1], reverse=True)
        rangeN = count
        if len(sortedDic) < count:
            rangeN = len(sortedDic)
        for i in range(rangeN):
            print(sortedDic[i])

def getWords(url):
    response = urllib.request.urlopen(url)
    html = response.read()
    wordParser = ContentParser()
    wordParser.feed(html.decode("utf-8"))
    wordParser.PrintTopUsedWords(25)

getWords("https://law.depaul.edu/Pages/default.aspx")

【问题讨论】:

  • 您导入了urlopen,但您尝试调用urllib.request.urlopen。要么打电话给urlopen,要么打电话给import urllib.request
  • 谢谢。这有帮助,现在可以了!

标签: python urllib urlopen


【解决方案1】:

在 Python 3 中最简单的方法是这样做

import urllib.request
data = urllib.request.urlopen("http://google.com")

【讨论】:

  • 谢谢。我也试过你的方法,效果很好!
  • 没问题,乐于助人!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 2012-08-24
  • 2016-11-23
  • 2020-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多