关于python list 写进txt中的问题
PHP中文网
PHP中文网 2017-04-18 10:25:04
0
3
632

各位大神好,我爬取腾讯新闻的新闻标题加入到一个列表当中,在用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('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中的内容

PHP中文网
PHP中文网

认证高级PHP讲师

全部回覆(3)
刘奇

文件操作放循環裡了?這樣每次操作每次開啟檔案每次寫入覆蓋…

# -*- 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('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()
Peter_Zhu

雷雷

伊谢尔伦

寫的動作放錯地方了

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!