名称错误: 名称“urllib”未定义。

13

代码:

import networkx as net
from urllib.request import urlopen
def read_lj_friends(g, name):
# fetch the friend-list from LiveJournal
response=urllib.urlopen('http://www.livejournal.com/misc/fdata.bml?user='+name)

错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'urllib' is not defined
5个回答

11

您已直接导入urlopen,因此应该直接引用它,而不是通过urllib引用:

response = urlopen('...')

6

您也可以尝试在Python 3中进行:

from six.moves import urllib

temp_file, _ = urllib.request.urlretrieve(url)

5

只需将import urllib放在你的代码顶部


1
尝试一下,请:
from urllib.request import urlopen

html = urlopen("http://www.google.com/")
print(html.read) # Content 

urllib是标准库的一部分。您无需安装不同的库urllib3。此外,urlopen返回类似文件对象的内容,而不是HTML。 - interjay
很复杂,抱歉。我正在修复它。谢谢你的提醒。 - Tolgahan ÜZÜN

0

对于你的情况:

import networkx as net
from urllib.request import urlopen
def read_lj_friends(g, name):
# fetch the friend-list from LiveJournal
response=urlopen('http://www.livejournal.com/misc/fdata.bml?user='+name)

1
欢迎来到SO。您的帖子包含与原始问题完全相同的代码,除了末尾的杂质反引号。请参阅https://stackoverflow.com/help/how-to-answer以获取指导。 - Nick
嘿,谢谢。代码中唯一需要更改的是删除最后一行代码中的urllib。请再看一遍。 - Banjali

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接