關(guān)于python list 寫進(jìn)txt中的問(wèn)題
問(wèn)題描述
各位大神好,我爬取騰訊新聞的新聞標(biāo)題加入到一個(gè)列表當(dāng)中,在用file.write()寫進(jìn) 新聞.txt的時(shí)候,為啥老是寫入列表的最后一個(gè)呢??
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))
這個(gè)是我爬取出來(lái)的東西(print(b)的結(jié)果)
這個(gè)是寫入txt中的內(nèi)容
問(wèn)題解答
回答1:文件操作放循環(huán)里了?這樣每次操作每次打開文件每次寫入覆蓋…
# -*- 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:
寫的動(dòng)作放錯(cuò)地方了
相關(guān)文章:
1. 如何分別在Windows下用Winform項(xiàng)模板+C#,在MacOSX下用Cocos Application項(xiàng)目模板+Objective-C實(shí)現(xiàn)一個(gè)制作游戲的空的黑窗口?2. 關(guān)于Java引用傳遞的一個(gè)困惑?3. 關(guān)于docker下的nginx壓力測(cè)試4. android clickablespan獲取選中內(nèi)容5. angular.js - angularjs的自定義過(guò)濾器如何給文字加顏色?6. python - TypeError: tryMsgcode() takes exactly 2 arguments (0 given)7. android - 啟動(dòng)模擬器的,報(bào)“Could not automatically detect an ADB binary……”,要怎么解決?8. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.9. javascript - 最終生成的jsBundle文件壓縮問(wèn)題10. node.js - 如何在服務(wù)器部署vuejs項(xiàng)目?
