2017-06-03 81 views
0

我想從python腳本輸出到excel。該腳本在Python中工作正常,但是當我嘗試執行導入CSV和編寫規則時,它不起作用。它說價格沒有在編劇中定義,我將如何打印多個項目。任何幫助,將不勝感激。蟒蛇美麗的湯輸出到excel

import csv 
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/manchester/?identifier=manchester&q=manchester&search_source=home&radius=0&pn=' + str(page) 
     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_name in soup.findAll('div', {'class': 'listing-details-address'}): 
    address = item_name.string 
    print(item_name.get_text(strip=True)) 
    for item_fame in soup.findAll('div', {'class' : 'listing-details-price text-price'}): 
     price = item_fame.string 
     print(item_fame.get_text(strip=True)) 

writer.writerow(price) 

trade_spider(1) 

回答

0

對象price沒有在任何地方你的腳本功能get_single_item_data的外側。在該功能之外,您的代碼無法識別具有該名稱的任何對象。此外,get_single_item_data不會從BeautifulSoup對象返回任何內容。它只打印它。你應該重寫你的函數是這樣的:

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

    #create list to contain addresses 
    addresses = [] 

    for item_name in soup.findAll('div', {'class': 'listing-details-address'}): 
     address = item_name.string 

     #add each address to the list 
     addresses.append(address) 

     print(item_name.get_text(strip=True)) 

    #create list for prices 
    prices = [] 

    for item_fame in soup.findAll('div', {'class' : 'listing-details-price text-price'}): 
     price = item_fame.string 

     #add prices to list 
     prices.append(price) 

     print(item_fame.get_text(strip=True)) 

    #alter the code to return the data structure you prefer. 
    return([addresses,prices]) 
+0

謝謝,我是新來的Python和必須做一些wrond,我嘗試了上面,它說回報外功能 – hello11

+0

這個錯誤意味着你需要把return語句放在函數中。在python中,這可能意味着你需要再次敲擊tab,以便比'def'行縮進一次。 –