Home  >  Q&A  >  body text

关于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('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中文网2740 days ago640

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-04-18 10:27:04

    File operations are placed in a loop? In this way, every operation, every file opening, every write is overwritten...

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

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:27:04

    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))

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:27:04

    The action I wrote is in the wrong place

    reply
    0
  • Cancelreply