2017-06-03 6 views
0

私は、pythonスクリプトからの出力をExcelに取得しようとしています。スクリプトはPythonでうまく動作しますが、CSVとwriterowのインポートルールを試してみるとうまくいきません。それはwriterowで定義されていない価格と、どのように私は複数の項目を印刷するだろうと言う。どんな助けもありがとう。python美しいスープの出力に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文を関数の中に置きます。これはおそらく、 'def'行よりもインデントされるようにもう一度タブを押す必要があることを意味します。 –

関連する問題