导入错误:没有模块名称urllib2

这是个人代码: html

import urllib2.request

response = urllib2.urlopen("http://www.google.com")
html = response.read()
print(html)

有什么帮助吗? python


#1楼

上面的内容在3.3中对我不起做用。 改用此方法(YMMV等) 工具

import urllib.request
url = "http://www.google.com/"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
print (response.read().decode('utf-8'))

#2楼

对于使用Python 2(测试版2.7.3和2.6.8)和Python 3(3.2.3和3.3.2+)的脚本,请尝试: 测试

#! /usr/bin/env python

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

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

#3楼

Python 3: google

import urllib.request

wp = urllib.request.urlopen("http://google.com")
pw = wp.read()
print(pw)

Python 2: url

import urllib
import sys

wp = urllib.urlopen("http://google.com")
for line in wp:
    sys.stdout.write(line)

虽然我已经测试了各自版本中的两个代码。 spa


#4楼

urllib2文档中所述code

urllib2模块已在Python 3中分为几个名为urllib.requesturllib.error 。 将源转换为Python 3时, 2to3工具将自动适应导入。 htm

因此你应该说 utf-8

from urllib.request import urlopen
html = urlopen("http://www.google.com/").read()
print(html)

您当前正在编辑的代码示例不正确,由于您说的是urllib.urlopen("http://www.google.com/")而不是urlopen("http://www.google.com/")


#5楼

那在python3中对我有用:

import urllib.request
htmlfile = urllib.request.urlopen("http://google.com")
htmltext = htmlfile.read()
print(htmltext)
相关文章
相关标签/搜索