首页 > Python怎么把输出整体写入CSV文件

Python怎么把输出整体写入CSV文件

由于我用Beatifulsoup抓取的是整段整段的文本内容,请问怎么把这些抓取整段整段的内容写入CSV?
以下是代码:

# -*- coding:utf-8 -*-
import re
from urllib2 import urlopen
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )

onehtml = urlopen("http://www.zhujiage.com.cn/article/List_2.html").read()
oneres = r'<A class=.{13} href=.(http://www.zhujiage.com.cn/article/.{6}/.{6}.html). title='
onecontent = re.findall(oneres,onehtml,re.S)
con = []
for i in range(1,31):
    html = urlopen(onecontent[i]).read()
    onejiexi = BeautifulSoup(html,'lxml')
    try:
        onesoup = onejiexi.findAll(id="content")[0]
        con.append(onesoup.text)

        res = '</a><a href=.(\d{6}_\d+.html).>'
        content = re.findall(res,html,re.S)
        new_content = sorted(set(content),key=content.index)
        for item in new_content:
            itemhtml = urlopen("http://www.zhujiage.com.cn/article/201607/" + item)
            jiexi = BeautifulSoup(itemhtml,'lxml')
            soup = jiexi.findAll(id="content")[0]
            con.append(soup.text)
    except IndexError:
        continue
f = open(r'f:/T.txt', 'w')
for t in range(len(con)):
    zhujia = con[t] + "\n"
    f.write(zhujia)
f.close()

csv文件就是文本文件,你可以直接按格式写入.
但是用python自带的csv模块更方便,我也没怎么用过,你可以参考以下链接.
官方文档
csdn上一个例子


这是python2的csv库的说明:https://docs.python.org/2/library/csv.html
这是python3的csv库的说明:https://docs.python.org/3/library/csv.html

照着上面的做就好了

【热门文章】
【热门文章】