Python urllib urlopen无法正常工作

Mat*_*Pan 10 python urllib

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

这是我的代码:

import urllib

sock = urllib.request.urlopen("http://diveintopython.org/") 
htmlSource = sock.read()                            
sock.close()                                        
print (htmlSource)  
Run Code Online (Sandbox Code Playgroud)

但我得到的错误如下:

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'
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 19

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

使用:

import urllib2

sock = urllib2.urlopen("http://diveintopython.org/") 
htmlSource = sock.read()                            
sock.close()                                        
print htmlSource
Run Code Online (Sandbox Code Playgroud)

Python 2 urllib2已被urllib.requestPython 3 取代.


小智 6

import requests
import urllib

link = "http://www.somesite.com/details.pl?urn=2344"

f = urllib.request.urlopen(link)
myfile = f.read()

writeFileObj = open('output.xml', 'wb')
writeFileObj.write(myfile)
writeFileObj.close()
Run Code Online (Sandbox Code Playgroud)

  • 通常,一个好的答案不仅包含代码,还包含一些关于固定内容的信息。 (2认同)

bra*_*ada 6

Python3中你可以使用urlliburllib3

网址库:

import urllib.request
with urllib.request.urlopen('http://docs.python.org') as response:
    htmlSource = response.read()
Run Code Online (Sandbox Code Playgroud)

urllib3:

import urllib3
http = urllib3.PoolManager()
r = http.request('GET', 'http://docs.python.org')
htmlSource = r.data
Run Code Online (Sandbox Code Playgroud)

更多详细信息可以在urllibpython文档中找到。