繁体   English   中英

使用python和漂亮的汤将抓取的数据输出到csv文件的问题

[英]Issues with outputting the scraped data to a csv file using python and beautiful soup

我试图将网站中的报废数据输出到一个csv文件中,首先我遇到了UnicodeEncoding错误,但是在使用了这段代码之后:

if __name__ == "__main__":
reload(sys)
sys.setdefaultencoding("utf-8")

我能够生成csv,下面是相同的代码:

import csv
import urllib2
import sys  
from bs4 import BeautifulSoup
if __name__ == "__main__":
    reload(sys)
    sys.setdefaultencoding("utf-8")
page =    urllib2.urlopen('http://www.att.com/shop/wireless/devices/smartphones.html').read()
soup = BeautifulSoup(page)
soup.prettify()
for anchor in soup.findAll('a', {"class": "clickStreamSingleItem"}):
        print anchor['title']        
        with open('Smartphones.csv', 'wb') as csvfile:
                spamwriter = csv.writer(csvfile, delimiter=',')        
                spamwriter.writerow([(anchor['title'])])     

但是我在输出的csv中仅获得一个设备名称,我没有任何编程背景,请原谅我的无知。 您能帮我找出问题所在吗?

这是意料之中的; 您每次找到一个元素都从头开始编写文件。 在循环浏览链接之前,仅打开文件一次 ,然后为找到的每个锚写行:

with open('Smartphones.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')        
    for anchor in soup.findAll('a', {"class": "clickStreamSingleItem"}):
        print anchor['title']        
        spamwriter.writerow([anchor['title'].encode('utf8')])   

使用w打开文件进行写入会首先清除该文件,而您正在对每个锚点进行操作。

至于您的unicode错误,请不惜一切代价避免更改默认编码。 相反,对行进行正确编码; 在上面的示例中,我这样做了,您可以删除整个.setdefaultencoding()调用(以及之前的reload() )。

暂无
暂无

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

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