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了