Skip to main content
 首页 » 编程设计

Python 忽略异常并从遇到异常的地方继续前进

2025年05月04日19duanxz

我遇到了一些问题。我正在使用 Python 解析一个大的 xml 文件。问题是 xml 文件是不可预测的,有时某些元素可能不存在于 xml 中,因此 Python 在查找它时会抛出异常。我希望 Python 简单地忽略此异常并继续寻找下一个元素。

这是我目前的代码,它不起作用。如果它找不到它正在寻找的元素,它只会抛出异常并移出 try-except block 。

# now we can parse the xml we fetched. 
        try: 
            user = {} 
            feedLinks = response.getElementsByTagName('gd:feedLink') 
            statistics = response.getElementsByTagName('yt:statistics')[0] 
            user['id'] = response.getElementsByTagName('id')[0].firstChild.data 
            user['channel_title'] = response.getElementsByTagName('title')[0].firstChild.data 
            user['profile_url'] = response.getElementsByTagName('link')[0].getAttribute('href') 
            user['author_name'] = response.getElementsByTagName('author')[0].firstChild.firstChild.data 
            user['author_uri'] = response.getElementsByTagName('uri')[0].firstChild.data 
            user['age'] = response.getElementsByTagName('yt:age')[0].firstChild.data 
            user['favourites_url'] = feedLinks[0].getAttribute('href') 
            user['contacts_url'] = feedLinks[1].getAttribute('href') 
            user['playlists'] = feedLinks[3].getAttribute('href') 
            user['subscriptions'] = feedLinks[4].getAttribute('href') 
            user['uploads'] = feedLinks[5].getAttribute('href') 
            user['new_subscription_videos'] = feedLinks[6].getAttribute('href') 
            user['statistics'] = {'last_access':statistics.getAttribute('lastWebAccess'),  
                            'subscriber_count':statistics.getAttribute('subscriberCount'),  
                            'video_watch_count':statistics.getAttribute('videoWatchCount'), 
                            'view_count':statistics.getAttribute('viewCount'),  
                            'total_upload_views':statistics.getAttribute('totalUploadViews')} 
            user['gender'] = response.getElementsByTagName('yt:gender')[0].firstChild.data 
            user['location'] = response.getElementsByTagName('yt:location')[0].firstChild.data 
            user['profile_pic_url'] = response.getElementsByTagName('media:thumbnail')[0].getAttribute('url') 
            user['username'] = response.getElementsByTagName('yt:username')[0].firstChild.data 
        except Exception, error: 
            # store the error for logging later 
            self.errors.append(str(error) + " from main.py:Crawler") 

有没有人有什么想法?

请您参考如下方法:

我会做的是遍历字典(我真的喜欢字典)并做你以前做的所有事情,但有所不同。像这样(未经测试):

for key in dicto: 
  try: user[key] = response.getElementsByTagName(dicto[key]) 
  except: print "mumble mumble"; continue 

将 getAttribute 内容附加到您的数据中不需要太多修改。