关于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. docker-compose中volumes的问题2. python 多进程 或者 多线程下如何高效的同步数据?3. vim - docker中新的ubuntu12.04镜像,运行vi提示,找不到命名.4. docker-compose 为何找不到配置文件?5. php - 想要远程推送emjio ios端怎么搞 需要怎么配合6. android - 添加multidex后在部分机型上产生anr的问题,该如何解决7. 一个走错路的23岁傻小子的提问8. angular.js - node.js中下载的angulae无法引入9. angular.js - Angular 刷新页面问题10. java - Hibernate查询的数据是存放在session中吗?
