Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
816 views
in Technique[技术] by (71.8m points)

关于python list 写进txt中的问题

各位大神好,我爬取腾讯新闻的新闻标题加入到一个列表当中,在用file.write()写进 新闻.txt的时候,为啥老是写入列表的最后一个呢??

from bs4 import BeautifulSoup
import requests
url = 'http://news.qq.com/'
wb_data = requests.get(url).text
soup = BeautifulSoup(wb_data,'lxml')
news_titles = soup.select('div.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中的内容


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

文件操作放循环里了?这样每次操作每次打开文件每次写入覆盖…

# -*- coding: utf-8 -*-
import sys

reload(sys)
sys.setdefaultencoding('utf-8')

from bs4 import BeautifulSoup
import requests
url = 'http://news.qq.com/'
wb_data = requests.get(url).text
soup = BeautifulSoup(wb_data,'lxml')
news_titles = soup.select('div.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 +"
"
    file.write(str(b))

file.close()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...