python爬蟲練習(xí)-爬下的數(shù)據(jù)保存

with open()語句

結(jié)構(gòu)

with open(name,mode,encoding) as file:
   file.writen()

name:包含文件名稱的字符串,可指定路徑,如'C:\Users\38153\Desktop\文件名.文件格式',如果不加路徑,它將會保存在你當(dāng)前工作目錄中。

mode:決定了打開文件的模式,只讀/寫入/追加等,
r------------------------只讀。若不存在文件會報錯
w-----------------------只寫。若不存在文件會自動新建
a-----------------------附加到文件尾

encoding:表示要寫入的編碼方式,一般為utf-8或gbk

file:表示我在代碼中對文件的命名。

以爬取豆瓣圖書top250為例

# -*-coding:utf-8-*-
import requests
from lxml import etree
import time
count = 1           #計數(shù)器

with open('test.txt','w',encoding = 'utf-8') as f: 
    #一頁25本書,一共10頁,循環(huán)十次。
    for i in range(10):
        #第一頁:https://book.douban.com/top250?start=0
        #第二頁:https://book.douban.com/top250?start=25
        #第三頁:https://book.douban.com/top250?start=50
        #。。。以此類推得:
        url = 'https://book.douban.com/top250?start={}'.format(i*25)


        data = requests.get(url).text               #獲取頁面的text
        s = etree.HTML(data)                        #解析data

        books = s.xpath('/html/body/div[3]/div[1]/div/div[1]/div/table')

        #print(scores)
        for div in books:
            
            name = div.xpath('./tr/td[2]/div[1]/a/@title')[0]
            athor= div.xpath('./tr/td[2]/p[1]/text()')[0]
            score = div.xpath('./tr/td[2]/div[2]/span[2]/text()')[0]
            quote = div.xpath('./tr/td[2]/p[2]/span/text()')

            print(count)
            #有的文章沒有qoute部分
            if len(quote)>0:
                #print("title:{}\tathor:{}\nscore:{}\tquote:{}\n\n".format(name,athor,score,quote)
                #直接輸入上文會產(chǎn)生問題,加上  .encode('GBK','ignore').decode('GBk') 也就是先用gbk編碼,
                #忽略掉非法字符,然后再譯碼
                f.write("title:{}\tathor:{}\nscore:{}\tquote:{}\n\n".format(name,athor,score,quote).encode('GBK','ignore').decode('GBk'))
            else:
                f.write("title:{}\tathor:{}\nscore:{}\n\n".format(name,athor,score))
            count += 1              #計數(shù)器加一

效果


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容