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

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

membalas semua(3)
刘奇

Operasi fail diletakkan dalam gelung? Dengan cara ini, setiap operasi, setiap pembukaan fail, setiap penulisan ditimpa...

# -*- 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
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))
伊谢尔伦

Tindakan bertulis berada di tempat yang salah

Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan