简体   繁体   中英

Writing multiple rows in excel using python

I am trying to draw data from tables from a url using a column of different numbers. I created a list of numbers and then input each number at the end of the url, draw the data from each unique link and input that data into a list. I then write the list to an excel file, but when I do, the data is written to one row when I need one row for each unique link.

import xlrd
from bs4 import BeautifulSoup
import requests
import csv
import urllib

sheet = xlrd.open_workbook('/Users/stevenschwab/Downloads/2016 Preliminary Assessments.xlsx')
sh = sheet.sheet_by_index(0)
numbers = sh.col_values(0)
data = []

for i in range(3,len(numbers)):
    data.append(int(numbers[i]))

for j in range(0,5):
    print(data[j])


for key in data:
    url = 'http://algonquin.northwoodsoft.com/display/PropertySearch.asp?cmd=DisplayDetails&ky= + key +'
    response = requests.get(url)
    html = response.content
    soup = BeautifulSoup(html,"html5lib")
    table = soup.find('center', attrs={'xmlns:dt':'urn:schemas-microsoft-com:datatypes'})
    rows = []

    for row in table.findAll('tr')[1:]:
        cells = []

        for cell in row.findAll('td'):
            cells.append(cell.text)
    rows.append(cells)

outfile = open('./property.csv', 'w')
writer = csv.writer(outfile)
writer.writerows([rows])

You are clearing your rows variable during every iteration of your loop. Move your rows = [] outside of your loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM