【问题标题】:AttributeError: 'str' object has no attribute 'read' Python urllib2AttributeError:'str'对象没有属性'read' Python urllib2
【发布时间】:2014-06-10 13:40:02
【问题描述】:

由于某种原因,我不断收到此错误,但我不知道为什么。我对 Python 还很陌生,所以请多多包涵。 我得到的错误是:AttributeError: 'str' object has no attribute 'read'

这是我的代码:

import re, urllib2
for i in range(0, 6):
    url = "http://www.gametracker.com/search/garrysmod/?searchipp=50&searchpge=  {0}#search".format(i)
    print url
    urlr = url.read()
    ip = re.compile(r"\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?):\d{1,6}\b")
    print ip.findall(urlr)

我希望有人可以帮助我。

【问题讨论】:

    标签: python http error-handling compiler-errors urllib2


    【解决方案1】:

    您忘记使用urlopen() 提出请求:

    urlr = urllib2.urlopen(url).read()
    

    此外,为避免Bad request 错误,请消除url 中的多余空格:

    url = "http://www.gametracker.com/search/garrysmod/?searchipp=50&searchpge=  {0}#search".format(i)
    #                                                                          ^
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 2013-10-28
      • 1970-01-01
      • 2018-12-01
      • 2015-09-30
      • 2021-10-22
      相关资源
      最近更新 更多