Python urllib urlopen 不起作用 [英] Python urllib urlopen not working

查看:37
本文介绍了Python urllib urlopen 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想通过使用 urllib 模块从实时网络中获取数据,所以我写了一个简单的例子

I am just trying to fetch data from a live web by using the urllib module, so I wrote a simple example

这是我的代码:

import urllib

sock = urllib.request.urlopen("http://diveintopython.org/") 
htmlSource = sock.read()                            
sock.close()                                        
print (htmlSource)  

但是我得到了如下错误:

But I got error like:

Traceback (most recent call last):
  File "D:\test.py", line 3, in <module>
    sock = urllib.request.urlopen("http://diveintopython.org/") 
AttributeError: 'module' object has no attribute 'request'

推荐答案

您正在阅读错误的文档或错误的 Python 解释器版本.您尝试在 Python 2 中使用 Python 3 库.

You are reading the wrong documentation or the wrong Python interpreter version. You tried to use the Python 3 library in Python 2.

使用:

import urllib2

sock = urllib2.urlopen("http://diveintopython.org/") 
htmlSource = sock.read()                            
sock.close()                                        
print htmlSource

Python 2 urllib2 被替换为 urllib.request 在 Python 3 中.

The Python 2 urllib2 library was replaced by urllib.request in Python 3.

这篇关于Python urllib urlopen 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆