2017-06-19 31 views
-3

下面出現的錯誤: 「if soup.find(text = bbb).parent.parent.get_text(strip = True AttributeError:'NoneType'object has沒有屬性「父」如何傳遞NoneTypes?所以爬蟲進行並不停止:

任何幫助將不勝感激,因爲我不能完全運行它,python只返回結果的錯誤,我需要它返回空,如果沒有項目,並繼續前進我試圖把一個IF語句,但是,這並不工作。

import csv 
import re 
import requests 
from bs4 import BeautifulSoup 

f = open('dataoutput.csv','w', newline= "") 
writer = csv.writer(f) 

def trade_spider(max_pages): 
    page = 1 
    while page <= max_pages: 
     url = 'http://www.zoopla.co.uk/for-sale/property/nottingham/?price_max=200000&identifier=nottingham&q=Nottingham&search_source=home&radius=0&pn=' + str(page) + '&page_size=100' 
     source_code = requests.get(url) 
     plain_text = source_code.text 
     soup = BeautifulSoup(plain_text) 
     for link in soup.findAll('a', {'class': 'listing-results-price text-price'}): 
      href = "http://www.zoopla.co.uk" + link.get('href') 
      title = link.string 
      get_single_item_data(href) 
     page += 1 

def get_single_item_data(item_url): 
    source_code = requests.get(item_url) 
    plain_text = source_code.text 
    soup = BeautifulSoup(plain_text) 

    for item_e in soup.findAll('table', {'class' : 'neither'}): 
     Sold = item_e.get_text(strip=True) 

bbb = re.compile('First listed') 
    try: 
     next_s = soup.find(text=bbb).parent.parent.get_text(strip=True) 
    except: 
     Pass 

try: 
writer.writerow([ Sold, next_s]) 
except: 
pass 

trade_spider(2) 
+0

指定'result = soup.find(...)',然後在繼續訪問屬性之前檢查'if result:'。或者'try:'然後'catch AttributeError:'。或者使用'getattr'。 – jonrsharpe

+0

謝謝,我很新的編碼,你能輸入你給我的代碼的例子,感謝您的幫助 – hello11

+0

然後,我建議通過例如運行。 https://docs.python.org/3/tutorial/來掌握這個基本的語法。 – jonrsharpe

回答

0

你的例外來自試圖在None訪問的屬性。你不打算這樣做,但要導致你的表情的一些早期部分變成None,你期望別的東西,後面的部分會突破。

具體來說,無論是soup.find(text=bbb)soup.find(text=bbb).parentNone(大概是前者,因爲我覺得None是返回值,如果find沒有找到任何東西)。

有幾種方法可以編寫代碼來解決此問題。您可以嘗試檢測它是否會提前發生(並執行其他操作),或者您可以繼續嘗試查找屬性並在失敗時作出反應。這兩種方法通常被稱爲「先看你飛躍」(LBYL)和「容易要求寬恕而不是權限」(EAFP)。

這裏的使用進行檢查,以確保價值不None訪問它們的屬性之前LBYL方法一的碼位:

val = soup.find(text=bbb) 
if val and val.parent: # I'm assuming the non-None values are never falsey 
    next_s = val.parent.parent.get_text(strip=True) 
else: 
    # do something else here? 

的EAFP方法可能比較簡單,但有一定的風險,它可以趕上其他意外的異常,而不是我們期望的那些(因此要小心使用在開發過程中這種設計方式):

try: 
    next_s = soup.find(text=bbb).parent.parent.get_text(strip=True) 
except AttributeError: # try to catch the fewest exceptions possible (so you don't miss bugs) 
    # do something else here? 

這不是明顯對我的代碼應該在做什麼「做別的事情在這裏」部分中的代碼ABOV即這可能是因爲你可以忽略這種情況,但是可能需要next_s的替代值供後面的代碼使用。如果沒有有用的替代價值,您可能希望提早退出該功能(使用return聲明)。

+0

謝謝Blckknght,感謝您的幫助 – hello11