鱼C论坛

 找回密码
 立即注册

爬虫801

已有 372 次阅读2018-8-1 21:24

数据存储
我们看一下如何利用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')
























路过

雷人

握手

鲜花

鸡蛋

全部作者的其他最新日志

评论 (0 个评论)

facelist

您需要登录后才可以评论 登录 | 立即注册

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-16 14:12

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

返回顶部