查看: 1492|回复: 3

Import error no urllib2 module

[复制链接]

19

主题

68

帖子

225

积分

论坛管理

Rank: 4

积分
225
发表于 2018-9-19 10:42:43 | 显示全部楼层 |阅读模式
这是我的代码:
  1. import urllib2.request
  2. response = urllib2.urlopen("http://www.google.com")
  3. html = response.read()
复制代码
报了如下错误
Import error no urllib2 module
回复

使用道具 举报

9

主题

74

帖子

185

积分

注册会员

Rank: 2

积分
185
发表于 2018-9-19 10:45:01 | 显示全部楼层
如urllib2文档中所述:
在Python 3中,该urllib2模块的几个模块重命名urllib.request和urllib.error。
所以你应该使用下面代码
  1. from urllib.request import urlopen
  2. html = urlopen("http://www.google.com/")
  3. print(html)
复制代码

回复

使用道具 举报

22

主题

107

帖子

266

积分

中级会员

Rank: 3Rank: 3

积分
266
发表于 2018-9-19 10:46:08 | 显示全部楼层
对于使用Python 2(测试版本2.7.3和2.6.8)和Python 3(3.2.3和3.3.2+)的脚本,请尝试:
  1. #! /usr/bin/env python

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

  8. html = urlopen("http://www.google.com/")
  9. print(html.read())
复制代码

回复

使用道具 举报

13

主题

53

帖子

131

积分

注册会员

Rank: 2

积分
131
发表于 2018-9-19 10:47:11 | 显示全部楼层
试试这个
  1. import urllib.request
  2. url = "http://www.google.com/"
  3. request = urllib.request.Request(url)
  4. response = urllib.request.urlopen(request)
  5. print (response.read().decode('utf-8'))
复制代码

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表