在 try-except 块中定义的未定义变量 [英] Undefined variable defined within try-except block

查看:44
本文介绍了在 try-except 块中定义的未定义变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码从网页 http://ajaxian.com 中抓取 XFN 内容但我收到未定义的变量错误:

I am using the below code to scrape over XFN content from web page http://ajaxian.com but I am getting undefined variable error:

我的代码如下:

'''
Created on Jan 11, 2013

@author: Somnath
'''
# Scraping XFN content from a web page
# -*-coding: utf-8 -*-

import sys
import urllib2
import HTMLParser
from BeautifulSoup import BeautifulSoup

# Try http://ajaxian.com
URL = sys.argv[0]

XFN_TAGS = set([
            'colleague',
            'sweetheart',
            'parent',
            'co-resident',
            'co-worker',
            'muse',
            'neighbor',
            'sibling',
            'kin',
            'child',
            'date',
            'spouse',
            'me',
            'acquaintance',
            'met',
            'crush',
            'contact',
            'friend',
            ])


try:
    page = urllib2.urlopen(URL)
except urllib2.URLError:
    print 'Failed to fetch ' + item

try:
    soup = BeautifulSoup(page)
except HTMLParser.HTMLParseError:
    print 'Failed to parse ' + item

anchorTags = soup.findAll('a')

for a in anchorTags:
    if a.has_key('rel'):
        if len(set(a['rel'].split()) & XFN_TAGS) > 0:
            tags = a['rel'].split()
            print a.contents[0], a['href'], tags

我的代码中有两个 try 块,它给出了一个错误未定义的变量:item.如果我想重新包含 try-except 块,我是否应该在 try 块之外给出变量、项目的空白定义?

I have two try blocks in my code and it is giving an error undefined variable : item. If I want to re-include the try-except blocks, should I give a blank definition of variable, item outside the try blocks?

P.S:请注意,这是一本书遵循的标准代码.我希望他们不会犯这样一个微不足道的错误.我这里有什么问题吗?

P.S: Please note that is a standard code followed from a book. And I expect that they would not have made such a trivial mistake. Am I getting something wrong here ?

推荐答案

假设您要打印加载失败的 URL,请尝试将其更改为 print 'Failed to fetch ' + URL.你实际上并没有在任何地方定义 item,所以 Python 不知道你的意思:

Assuming that you want to print the URL that failed to load, try changing it to print 'Failed to fetch ' + URL. You aren't actually defining item anywhere, so Python doesn't know what you mean:

try:
    page = urllib2.urlopen(URL)
except urllib2.URLError:
    print 'Failed to fetch ' + URL

在您的第二个块中,将 item 也更改为 URL(假设您要显示的错误显示的是 URL 而不是内容).

And in your second block, change item to URL as well (assuming the error you want to display shows the URL and not the content).

try:
    soup = BeautifulSoup(page)
except HTMLParser.HTMLParseError:
    print 'Failed to parse ' + URL

这篇关于在 try-except 块中定义的未定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆