如何从urllib读取lines()

2024-10-05 10:13:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个使用http的程序,我想从http读取数据:

data = urllib.request.urlopen(someAddress).read()

并从中准备一系列行,比如用readlines()方法返回文件行。

怎么做?


Tags: 文件方法程序httpreaddatarequest读取数据
2条回答

urlopen()返回一个类似于文件的对象,并支持.readlines()

response = urllib.request.urlopen(someAddress)

lines = response.readlines():

它还支持迭代:

response = urllib.request.urlopen(someAddress)

for line in response:

您已经在响应对象上调用了.read();您也可以在该对象上调用str.splitlines()

lines = data.splitlines(True)

其中True告诉str.splitlines()保留行尾。

我通常做一些类似的事情。我使用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)

相关问题 更多 >

    热门问题