AttributeError:'NoneType'对象没有Python WebCrawler的属性'strip'

时间:2011-08-02 21:48:33

标签: python html twitter web-crawler

我正在编写一个python程序来使用urllib2,api的python twitter包装器和BeautifulSoup的组合来抓取twitter。但是,当我运行我的程序时,我收到以下类型的错误:

ray_krueger 拉斐尔·拿度

Traceback (most recent call last):
  File "C:\Users\Public\Documents\Columbia Job\Python Crawler\Twitter Crawler\crawlerversion9.py", line 78, in <module>
    crawl(start_follower, output, depth)
  File "C:\Users\Public\Documents\Columbia Job\Python Crawler\Twitter Crawler\crawlerversion9.py", line 74, in crawl
    crawl(y, output, in_depth - 1)
  File "C:\Users\Public\Documents\Columbia Job\Python Crawler\Twitter Crawler\crawlerversion9.py", line 74, in crawl
    crawl(y, output, in_depth - 1)
  File "C:\Users\Public\Documents\Columbia Job\Python Crawler\Twitter Crawler\crawlerversion9.py", line 64, in crawl
    request = urllib2.Request(new_url)
  File "C:\Python28\lib\urllib2.py", line 192, in __init__
    self.__original = unwrap(url)
  File "C:\Python28\lib\urllib.py", line 1038, in unwrap
    url = url.strip()
AttributeError: 'NoneType' object has no attribute 'strip'

我完全不熟悉这种类型的错误(python新手)并且在线搜索它产生的信息非常少。我也附上了我的代码,但你有什么建议吗?

感谢名单 Snehizzy

import twitter
import urllib
import urllib2
import htmllib
from BeautifulSoup import BeautifulSoup
import re

start_follower = "NYTimeskrugman" 
depth = 3
output = open(r'C:\Python27\outputtest.txt', 'a') #better to use SQL database thanthis

api = twitter.Api()

#want to also begin entire crawl with some sort of authentication service 

def site(follower):
    followersite = "http://mobile.twitter.com/" + follower
    return followersite

def getPage(follower): 
    thisfollowersite = site(follower)
    request = urllib2.Request(thisfollowersite)
    response = urllib2.urlopen(request)
    return response

def getSoup(response): 
    html = response.read()
    soup = BeautifulSoup(html)
    return soup

def get_more_tweets(soup): 
    links = soup.findAll('a', {'href': True}, {id : 'more_link'})
    for link in links:
        b = link.renderContents()
        if str(b) == 'more':
            c = link['href']
            d = 'http://mobile.twitter.com' +c
            return d

def recordlinks(soup,output):
    tags = soup.findAll('div', {'class' : "list-tweet"})#to obtain tweet of a follower
    for tag in tags: 
        a = tag.renderContents()
        b = str (a)
        output.write(b)
        output.write('\n\n')

def checkforstamp(soup):
    times = nsoup.findAll('a', {'href': True}, {'class': 'status_link'})
    for time in times:
        stamp = time.renderContents()
        if str(stamp) == '3 months ago':
            return True

def crawl(follower, output, in_depth):
    if in_depth > 0:
        output.write(follower)
        a = getPage(follower)
        new_soup = getSoup(a)
        recordlinks(new_soup, output)
        currenttime = False 
        while currenttime == False:
            new_url = get_more_tweets(new_soup)
            request = urllib2.Request(new_url)
            response = urllib2.urlopen(request)
            new_soup = getSoup(response)
            recordlinks(new_soup, output)
            currenttime = checkforstamp(new_soup)
        users = api.GetFriends(follower)
        for u in users[0:5]:
            x = u.screen_name 
            y = str(x)
            print y
            crawl(y, output, in_depth - 1)
            output.write('\n\n')
        output.write('\n\n\n')

crawl(start_follower, output, depth)
print("Program done. Look at output file.")

4 个答案:

答案 0 :(得分:1)

  

AttributeError:'NoneType'对象没有属性'strip'

这正是它所说的内容:url.strip()首先需要确定url.strip是什么,即查找strip的{​​{1}}属性。此操作失败,因为urlurl,即类型为'NoneType' object的对象,即特殊对象NoneType

预计None应该是url,即文本字符串,因为它们具有str属性。

这发生在strip内,即File "C:\Python28\lib\urllib.py"模块。那不是你的代码,所以我们回顾一下异常跟踪,直到找到我们写的东西:urllib。我们只能假设我们传递给request = urllib2.Request(new_url)模块的new_url最终在urllib2内的某个地方成为url变量。

那么urllib来自哪里?我们查找有问题的代码行(注意异常回溯中有一个行号),我们看到前一行是new_url,所以我们使用{{1}的结果}。

对此功能的分析表明,它搜索了一些链接,试图找到一个标记为“更多”的链接,并为我们找到它找到的第一个链接的URL。我们没有考虑的情况是没有这样的链接。在这种情况下,函数刚到达结尾,并隐式返回None(这就是Python如何处理在没有显式返回的情况下到达末尾的函数,因为Python中没有返回类型的规范,因为必须始终返回值) ,这是价值的来源。

据推测,如果没有“更多”链接,那么我们就不应该试图完全遵循这个链接。因此,我们通过显式检查此new_url = get_more_tweets(new_soup)返回值并在此情况下跳过get_more_tweets来修复错误,因为没有要关注的链接。

顺便说一下,对于尚未确定的None而不是您当前使用的urllib2.Request值,此None值将是更惯用的“占位符”值。您可能还会考虑在变量和方法名称中使用下划线分隔单词以使其更易于阅读。 :)

答案 1 :(得分:0)

当你这样做时

request = urllib2.Request(new_url)
<{1>}中的

crawl()new_url。当您从None获得new_url时,这意味着get_more_tweets(new_soup)正在返回get_more_tweets()

这意味着永远无法联系到None,这意味着return d永远不会为真,或者str(b) == 'more'没有返回任何链接,因此soup.findAll()什么都不做。

答案 2 :(得分:0)

当您这样做时:request = urllib2.Request(new_url)new_url应该是一个字符串,此错误表明它是None

您从get_more_tweets函数获取new_url的值,因此,它在某处返回None

def get_more_tweets(soup): 
    links = soup.findAll('a', {'href': True}, {id : 'more_link'})
    for link in links:
        b = link.renderContents()
        if str(b) == 'more':
            c = link['href']
            d = 'http://mobile.twitter.com' +c
            return d

当我们查看此代码时,该函数仅在某个链接上的str(b)=="more"时返回,因此您的问题是“为什么从不str(b)==”更多“发生?”。

答案 3 :(得分:0)

您将None而不是字符串传递给urllib2.Request()。查看代码,这有时意味着new_urlNone。看看你的get_more_tweets()函数,这是这个变量的来源,我们看到了这个:

def get_more_tweets(soup): 
    links = soup.findAll('a', {'href': True}, {id : 'more_link'})
    for link in links:
        b = link.renderContents()
        if str(b) == 'more':
            c = link['href']
            d = 'http://mobile.twitter.com' +c
            return d

此函数仅在b"more"时才返回值,因为return语句在if下缩进。如果它等于任何其他值,则不返回任何值(即None)。

您需要始终在此处返回有效的网址,或者需要先检查None返回值,然后再将其传递给urllib2.Request()