Writerow不会将某些变量打印到csv文件中

时间:2017-04-04 21:10:02

标签: python csv

以下代码无法将名称和地址变量写入csv文件。当我使用数字或单词测试它,或者“写入”变量时,这些将记录在csv中,但“Writeaddress”和“WriteName”将不会*。(另外,使用这些变量的原始来源也会离开空白)

import requests, sys, pyperclip, bs4, csv
StationList = open('CTA Station Addresses.csv', 'w', newline='')
StationWrite = csv.writer(StationList)
for i in range(149):
    id = str(i)
    res = requests.get('http://www.transitchicago.com/travel_information  /station.aspx?StopId=' + id)
    res.raise_for_status()
    Station = bs4.BeautifulSoup(res.text)
    Name = Station.select('.rtehdng')
    Address = Station.select('#ctl07_divAddress')
    Write = 0
    if Name == []:
        print('missing name')
        Write = 1
    else:
        #print(Name[0].getText())
        WriteName = Name[0].getText()
        pass
    if Address == []:
        print('missing address')
        Write = 1
    else:
        #print(Address[0].getText())
        WriteAddress = Address[0].getText()
        pass
    if Write == 0:
        StationWrite.writerow([Write, WriteName, WriteAddress])
    Write = 0
StationList.close()

*(我可以做“writerows([3,Write,Writename]),CSV行将是”3,0“,

1 个答案:

答案 0 :(得分:0)

我无法重现您的错误,但您获得的数据嵌入了新行和空格,这可能会使csv看起来很奇怪。我已经清理了脚本并在编写csv之前清理了数据,最后得到了站点,地址条目。我没有看到需要编写Write,因为它在你的脚本中始终为0,甚至不存在于我的脚本中,因为我利用了异常处理。

import requests, sys, pyperclip, bs4, csv

with open('CTA Station Addresses.csv', 'w', newline='') as StationList:
    StationWrite = csv.writer(StationList)
    for i in range(149):
        _id = str(i)
        res = requests.get('http://www.transitchicago.com/travel_information/station.aspx?StopId=' + _id)
        res.raise_for_status()
        Station = bs4.BeautifulSoup(res.text, 'lxml')
        try:
            name = Station.select('.rtehdng')[0].getText().strip()
            address = Station.select('#ctl07_divAddress')[0].getText().splitlines()[-1].strip()
        except IndexError as e:
            print("No data for station", _id)
            continue
        if not name or not address:
            print('Empty elements for station', _id)
            continue
        print(repr(name), repr(address))
        StationWrite.writerow([name, address])