簡體   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