【问题标题】:How to readlines() from urllib如何从 urllib 读取行()
【发布时间】:2014-06-01 14:41:06
【问题描述】:

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

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

并从中准备行列表,例如通过文件的 readlines() 方法返回行。

怎么做?

【问题讨论】:

  • 您自己也可以轻松尝试。

标签: python http urllib


【解决方案1】:

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() 保留行尾。

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 谢谢。这适用于我想要做的事情,即将所有行放在列表形式中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 2017-09-20
    • 2017-02-24
    • 1970-01-01
    • 2013-01-25
    相关资源
    最近更新 更多