简体   繁体   English

使用python在Excel中编写多行

[英]Writing multiple rows in excel using python

I am trying to draw data from tables from a url using a column of different numbers. 我正在尝试使用一列不同的数字从URL的表格中提取数据。 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. 我创建了一个数字列表,然后在url的末尾输入每个数字,从每个唯一链接中提取数据,然后将该数据输入到列表中。 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. 然后,我将列表写入一个excel文件,但是当我这样做时,当每个唯一链接需要一行时,数据就会写入一行。

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. 您将在循环的每次迭代中清除rows变量。 Move your rows = [] outside of your loop. 将您的rows = []移出循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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