python爬虫学习-使用pandas保存内容到本地

本文介绍了在Python爬虫过程中如何使用pandas保存内容到本地,并探讨了with open与open()的区别,以及在翻页抓取中如何使用str.format()和range()函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、在学习pandas用法之前,了解过with open的用法,代码参上:

import requests
from lxml import etree

url='https://book.douban.com/subject/1882933/comments/'
r=requests.get(url).text

s=etree.HTML(r)
file=s.xpath('//*[@id="comments"]/ul[1]/li/div[2]/p/span/text()')

with open('pinglun.txt','w',encoding='utf-8') as p:#使用with open()新建对象p
    for i in file:
        print(i)
        p.write(i+"\n")#换行写入数据,文件保存在当前工作目录

可能会遇到的问题:

使用open函数进行保存时,为什么要用with open?

open()也是可以的,但是如果用open,那么在函数后面就一定要加上close。

例如

f=open('test.txt',encoding='utf-8') 

data=f.read() 

print(data)

f.close() 

如果最后不加上close的话,文件就会一直占用系统资源,可能导致其他不安全隐患。

但是这样写起来又很麻烦,所以python自己又搞了一个with open,默认会进行关闭,就不需要每次都加close了。

 

2、pandas进行保存的代码

import requests
from lxml import etree

url='https://book.douban.com/subject/1882933/comments/'
r=requests.get(url).t
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值