2017-06-19 34 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