对把解析出来的文档写入文件当中

import requests
#下载百度首页,requests库将下载结果封装为response类
response = requests.get(“http://www.baidu.com”)
#dir可以查看类的内部结构
#暴力调试就是一个一个试,可以了解类的内部方法行为

print(dir(response))

#text会使用默认的编码方式转换成字符串
text = response.text
#with as能够实现自动清理的条件是相应类必须实现__enter__,__exit__两个magic方法
with open(“baidu.html”,"+w") as f:
#response.content是bytes类型使用decode方法还原为相应编码的字符串
f.write(response.content.decode(“utf-8”))

class CustomWithAs(object):
def init(self):
pass
def test(self):
print(“test with as”)
#两个下划线开始的方法成为magic方法
def enter(self):
print(“进入enter方法”)
def exit(self, exc_type, exc_val, exc_tb):
print(“with 执行完毕,自动调用了exit”)

with CustomWithAs() as custom_wa:
#在代码块中完全没有调用这个方法,而是上面的with自动调用上面的__enter__和__exit__的方法
print(“test”)

猜你喜欢

转载自blog.csdn.net/weixin_44274975/article/details/87913864