首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用漂亮的soup将刮过的数据更新到已经存在的csv中的问题

使用漂亮的soup将刮过的数据更新到已经存在的csv中的问题
EN

Stack Overflow用户
提问于 2012-12-26 07:41:48
回答 1查看 120关注 0票数 1

我想要更新从网页上刮到的数据到一个已经存在的csv,这是我第一次运行抓取代码时生成的。我希望新的数据被附加在已经刮过的行下面。

下面是我用来抓取数据和编写csv的代码:

代码语言:javascript
复制
import csv
import urllib2
import sys
import time
from bs4 import BeautifulSoup
from itertools import islice
page = urllib2.urlopen('http://shop.ee.co.uk/mobile-phones/pay-monthly/').read()
soup = BeautifulSoup(page)
soup.prettify()
with open('EE_AppendTesting.csv', 'a') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    #spamwriter.writerow(["Date","Month","Day of Week","Device Name","Price","Plan Monthly Price"])    
    items = soup.findAll('h2', {"class":"heading2 no-margin-top"})
    prices = soup.findAll('span', {"class": "price"})
    monthly = soup.findAll('div',{"class":"mrc-holder"})
    for item, price, monthly1 in zip(items, prices, monthly):
        textcontent = u' '.join(islice(monthly1.stripped_strings, 2, 3, 1))
        if textcontent:
            spamwriter.writerow([time.strftime("%Y-%m-%d"),time.strftime("%B"),time.strftime("%A") ,unicode(item.string).encode('utf8').strip(),unicode(price.string).encode('utf8').replace('£','£').strip(),unicode(textcontent).encode('utf8').replace('£','£').strip()])

现在,每次我运行代码时,新数据都会在每个数据条目之间追加空行的。以下是所附csv的示例:

代码语言:javascript
复制
26-12-2012  December    Wednesday   Nokia Lumia 920 White   £ 19.99 £46.00
26-12-2012  December    Wednesday   iPhone 5 64GB Black £ 139.99    £56.00

26-12-2012  December    Wednesday   Nokia Lumia 820 FREE    £36.00

26-12-2012  December    Wednesday   iPhone 5 16GB White £ 19.99 £56.00
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-26 08:38:05

我在代码中使用了“lineterminator='\n‘”方法来解决上述问题。更新后的代码如下所示:

代码语言:javascript
复制
with open('EE_AppendTesting.csv', 'a') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',',lineterminator='\n')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14037518

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档