关于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. 如何解决Centos下Docker服务启动无响应,且输入docker命令无响应?2. 关docker hub上有些镜像的tag被标记““This image has vulnerabilities””3. docker绑定了nginx端口 外部访问不到4. 我在centos容器里安装docker,也就是在容器里安装容器,报错了?5. docker镜像push报错6. sql语句,通过一个中文怎么能查询数据表中的这个字段第一个字是这个中文呢7. 在windows下安装docker Toolbox 启动Docker Quickstart Terminal 失败!8. golang - 用IDE看docker源码时的小问题9. mac里的docker如何命令行开启呢?10. docker内创建jenkins访问另一个容器下的服务器问题

网公网安备