關于python list 寫進txt中的問題
問題描述
各位大神好,我爬取騰訊新聞的新聞標題加入到一個列表當中,在用file.write()寫進 新聞.txt的時候,為啥老是寫入列表的最后一個呢??
from bs4 import BeautifulSoupimport requestsurl = ’http://news.qq.com/’wb_data = requests.get(url).textsoup = BeautifulSoup(wb_data,’lxml’)news_titles = soup.select(’p.text > em.f14 > a.linkto’)for n in news_titles: title = n.get_text() link = n.get('href') file = open(’/Users/sufan/Desktop/新聞.txt’, ’w’) b = [] b.append(title + ’鏈接’ + link) file.write(str(b))
這個是我爬取出來的東西(print(b)的結果)
這個是寫入txt中的內容
問題解答
回答1:文件操作放循環里了?這樣每次操作每次打開文件每次寫入覆蓋…
# -*- coding: utf-8 -*-import sysreload(sys)sys.setdefaultencoding(’utf-8’)from bs4 import BeautifulSoupimport requestsurl = ’http://news.qq.com/’wb_data = requests.get(url).textsoup = BeautifulSoup(wb_data,’lxml’)news_titles = soup.select(’p.text > em.f14 > a.linkto’)file = open(’新聞.txt’, ’a’)for n in news_titles: title = n.get_text() link = n.get('href') b = str(title) + ’ 鏈接: ’ + link +'n' file.write(str(b))file.close()回答2:
for n in news_titles: title = n.get_text() link = n.get('href') b = [] b.append(title + ’鏈接’ + link) with open(’/Users/sufan/Desktop/新聞.txt’, ’w’) as file: file.write(str(b))回答3:
寫的動作放錯地方了
相關文章:
1. python - oslo_config2. python - 請問這兩個地方是為什么呢?3. mysql優化 - mysql 一張表如果不能確保字段列長度一致,是不是就不需要用到char。4. javascript - 按鈕鏈接到另一個網址 怎么通過百度統計計算按鈕的點擊數量5. python2.7 - python 正則前瞻 后瞻 無法匹配到正確的內容6. 請教一個mysql去重取最新記錄7. 大家都用什么工具管理mysql數據庫?8. 人工智能 - python 機器學習 醫療數據 怎么學9. mysql - Sql union 操作10. php - 有關sql語句反向LIKE的處理
