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ù)器加一
效果

