【问题标题】:python beautiful soup output into excelpython 美丽的汤输出到excel
【发布时间】:2017-06-03 17:01:20
【问题描述】:

我正在尝试将 python 脚本的输出转换为 excel。该脚本在 Python 中运行良好,但是当我尝试执行导入 CSV 和 writerow 规则时它不起作用。它说价格未在 writerow 中定义,我将如何打印多个项目。任何帮助,将不胜感激。

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)

【问题讨论】:

    标签: python excel csv beautifulsoup


    【解决方案1】:

    对象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])
    

    【讨论】:

    • 谢谢,我是 python 新手,肯定做错了什么,我尝试了上面的方法,它说 return 是外部函数
    • 这个错误意味着你需要把return语句放在函数里面。在 python 中,这可能意味着您需要再按一次制表符,以便它比def 行缩进一次。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 2019-10-12
    相关资源
    最近更新 更多