数据存储
我们看一下如何利用python存储txt格式文本文件
我们首先用requests获取源代码,再用相关解析库解析,接下来保存到文本中。
import requests
from pyquery import PyQuery as pq
url='http://www.zhihu.com/explore'
headers={'User-Agent':"Mozilla/5.0(Macintosh; Intel Mac OS X 10_12_3)AppleWebKit/537.36(KHTML,like Gecko)Chrome/58.0.3029.110 Safari/537.36"}
html=requests.get(url,headers=headers).text
doc=pq(html)
items=doc('.explore-tab.feed-item').items()
for item in items:
question=item.find('h2').text()
author=item.find('.author-link-line').text()
answer=pq(item.find('.content').html()).text()
file=open('explore.txt','a',encoding='utf-8')
file.write('/n'.join([question,author,answer]))
file.write('/n'+'='*50+'/n')
file.colse()
这里首先requests提取了内容,然后利用open()方法打开文件,write()写入文件最后用close()关闭
open()方法第一个参数是保存的目标文件名称,第二个参数a表示以追加方式写入文本。
简化写法:
使用with as控制文件写入,且可以省去close()
with open('explore.txt','a',encoding='utf-8') as file:
dile.write('/n'.join([question,author,answer]))
file.write('/n'+'='*50+'/n')
如果想要将保存时将原文清空的话,把第二个参数改为w。
with open('explore.txt','w',encoding='utf-8') as file:
dile.write('/n'.join([question,author,answer]))
file.write('/n'+'='*50+'/n')