Django-异常类型:KeyError

时间:2015-07-05 17:43:07

标签: python django python-2.7 twitter beautifulsoup

我正在开发一个应用程序,我正在使用使用Twitter登录登录我的应用程序的用户的Twitter帐户URL,使用BeautifulSoup和{{来删除总推文数量和关注者数量1}}。

views.py

urllib2

但是,这是我在POST请求中遇到的错误:

import urllib2
from bs4 import BeautifulSoup

def fillform(request):
    if request.method == 'POST':
        profile = ['Tweets', 'Followers']
        followers = ''
        tweets = ''
        form = EvangelizedForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=True)
            link = obj.twitter_url
            dic = {}
            r = urllib2.urlopen(link)
            src = r.read()
            res = BeautifulSoup(src)
            for p, d in zip(profile, res.find_all('span', { 'data-is-compact': "true"})):
                dic[p] = d
            followers = dic['Followers']
            tweets = dic['Tweets']  
            obj.twitter_followers = followers
            obj.total_tweets = tweets
            obj.save()
            return index(request)
        else:
            form.errors
    else:
        #form = EvangelizedForm()
        if request.user.is_authenticated():
            form = EvangelizedForm(initial={'first_name': request.user.first_name,
                                                'twitter_url': 'https://www.twitter.com/' + request.user.username,
                                                    'last_name': request.user.last_name})
        else:
            form = EvangelizedForm()    

    context = RequestContext(request,
                           {'request': request,
                            'user': request.user, 'form':form})    

    #return render(request, 'rango/fillform.html', {'form': form, 'context_instance':context})  
    return render_to_response('rango/fillform.html',
                             context_instance=context)

我尝试在本地运行我的抓取脚本,键Traceback: File "C:\PYTHON27\lib\site-packages\django\core\handlers\base.py" in get_response 111. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Django\GetEvangelized\rango\views.py" in fillform 30. followers = dic['Followers'] Exception Type: KeyError at /rango/fillform/ Exception Value: 'Followers' Followers会返回存储在字典中的值。在我看来,似乎出了什么问题?我是否以错误的方式导入Django中的TweetsBeautifulSoup模块?或者在我的方法中是否有其他错误?

0 个答案:

没有答案