[問題] python 將爬出來的資料匯出至檔案

看板Python作者 (渣)時間9年前 (2016/03/08 11:18), 9年前編輯推噓1(105)
留言6則, 3人參與, 最新討論串1/2 (看更多)
大家好,小弟本身沒有什麼程式背景 最近開始接觸到了 Python 但是遇到了一些問題想請教一下大家 小弟按照著教學把網路上要得資訊爬下來 print 也有資料出來 但是希望可以把print 出來的資料輸出成 txt or csv 但是一直無法成功,想請教一下前輩是哪邊的邏輯有問題 import requests from bs4 import BeautifulSoup res = requests.get("http://www.yodobashi.com/%E3%82%B9%E3%83%81%E3%83%BC%E3%83%A0%E3%82%AA%E3%83%BC%E3%83%96%E3%83%B3%E3%83%AC%E3%83%B3%E3%82%B8/ct/6567_500000000000000211/?count=48&discontinued=false&disptyp=01&oword=Hitachi&page=1&searchtarget=prodname&sorttyp=COINCIDENCE_RANKING&ginput=Hitachi") soup = BeautifulSoup(res.text) for item in soup.select('.pListBlock'): f = open('A.txt', 'w', encoding = 'UTF-8') f.write (item.select('.pName')[0].text,item.select('.red')[0].text) f.close () requests.get的縮址 http://goo.gl/PS3c4K 感謝大家 @@ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.227.175.246 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1457407103.A.502.html ※ 編輯: brightsu (125.227.175.246), 03/08/2016 11:19:34

03/08 15:29, , 1F
可以排一下版嗎...看的眼花瞭亂
03/08 15:29, 1F
抱歉,小第一次發文沒注意到直接貼上所有的排版都跑掉了 ※ 編輯: brightsu (125.227.175.246), 03/08/2016 16:44:12

03/08 16:53, , 2F
你順序搞錯了, open放在for裡就會一直重覆開, 然後一直
03/08 16:53, 2F

03/08 16:54, , 3F
蓋掉你已存進去的資料, 除非你用a+
03/08 16:54, 3F

03/08 16:55, , 4F

03/08 18:40, , 5F
W改掉 因為這樣每次存都是全砍光重寫一次
03/08 18:40, 5F

03/10 22:34, , 6F
f open 跟f close 都放到回圈外
03/10 22:34, 6F
文章代碼(AID): #1MtaH_K2 (Python)
文章代碼(AID): #1MtaH_K2 (Python)