2024-10-05 10:13:41 发布
网友
我有一个使用http的程序,我想从http读取数据:
data = urllib.request.urlopen(someAddress).read()
并从中准备一系列行,比如用readlines()方法返回文件行。
怎么做?
urlopen()返回一个类似于文件的对象,并支持.readlines():
urlopen()
.readlines()
response = urllib.request.urlopen(someAddress) lines = response.readlines():
它还支持迭代:
response = urllib.request.urlopen(someAddress) for line in response:
您已经在响应对象上调用了.read();您也可以在该对象上调用str.splitlines():
.read()
str.splitlines()
lines = data.splitlines(True)
其中True告诉str.splitlines()保留行尾。
True
我通常做一些类似的事情。我使用urllib2,但它不应该如此不同:
from urllib2 import Request, urlopen def getPage(link, splitting = '\n'): request = Request(link) try: response = urlopen(request) except IOError: return -1 else: the_page = response.read() return the_page.split(splitting)
urlopen()
返回一个类似于文件的对象,并支持.readlines()
:它还支持迭代:
您已经在响应对象上调用了
.read()
;您也可以在该对象上调用str.splitlines()
:其中
True
告诉str.splitlines()
保留行尾。我通常做一些类似的事情。我使用urllib2,但它不应该如此不同:
相关问题 更多 >
编程相关推荐