2015-08-15 72 views
3

我有一個IP地址的文本文件,每個在自己的行。以下腳本將遍歷列表並查詢該站點以查找與IP匹配的域並將它們打印到文件中。如果每個IP都有結果,這可以正常工作,但是當網站沒有返回域時,我會得到以下錯誤BeautifulSoup無法匹配該屬性,並且腳本失敗。BeautifulSoup沒有發現屬性

AttributeError: 'NoneType' object has no attribute 'contents'

我試圖在那裏拋出一個if語句,但無法讓它工作。

如何讓我的腳本打印「無結果」並繼續瀏覽其餘的IP,如果在該屬性中找不到域?

import urllib2 
from BeautifulSoup import BeautifulSoup 
import StringIO 

ipfile = open("test.txt", "r") 
for line in ipfile: 
    line = line.strip() 
    site = 'http://bgp.he.net/ip/' + line + '#_dns' 
    #print site 

    s = StringIO.StringIO(site) 
    for line2 in s: 
     req = urllib2.Request(line2) 
     req.add_header('User-agent', 'Mozilla/5.0 (Windows NT 5.1; rv:23.0) Gecko/20100101 Firefox/23.0') 
     html = urllib2.urlopen(req) 

     soup = BeautifulSoup(html.read()) 
     #print soup.prettify() 
     results = soup.find("div", {"id": "dns"}).a.contents 
     results = '\n'.join(results) 
     print results 

     f = open('out.txt', 'a') 
     print >>f, results 
     f.close 

回答

2

使用try/excepterror handling

try: 
    soup = BeautifulSoup(html.read()) 
    #print soup.prettify() 
    results = soup.find("div", {"id": "dns"}).a.contents 
    results = '\n'.join(results) 
    print results 

    f = open('out.txt', 'a') 
    print >>f, results 
    f.close 
except: 
    print 'No result' 

如果try塊中發生任何錯誤,那麼它會立即停止,並轉到except塊。這樣可以讓你的代碼繼續運行,而不必停下來。

如果你想獲得真正具體的,你可以告訴Python只處理異常,如果它是某種類型的,在這種情況下,你可以這樣做:

except AttributeError:,而不是except:

+1

謝謝!我將進一步閱讀關於未來錯誤處理的內容。 – Christopher

+0

好主意,這是學習和提高的最佳方式:) – Parker

1

您可以使用嘗試/除了,除了AttributeError只(這是不好的,趕上他們所有,因爲你會忽略潛在的錯誤,如果你趕上他們)例如 -

try: 
    results = soup.find("div", {"id": "dns"}).a.contents 
    results = '\n'.join(results) 
    print results 
    with open('out.txt', 'a') as f: 
     print >>f, results 
except AttributeError: 
    print '<Message when no <a> tag found inside `div` with `id` dns>' 
+0

謝謝你的協助! – Christopher

相關問題