简单的案例-爬取百度首页
from urllib import request
'''
爬取百度首页
'''
# 确定爬去目标
base_url = 'http://www.baidu.com' # 发起http请求 返回一个类文件对象
response = request.urlopen(url=base_url) # 获取相应内容
html = response.read() # 把bytes类型转换成utf-8编码的字符串类型
html = html.decode('utf-8') # 写入文件
with open('baidu.html','w',encoding='utf-8') as f:
f.write(html)
response = request.urlopen(url=base_url)
传入要爬取的网页的url,返回一个类文件对象,它可以像文件对象一样被操作。
请求地址url,一般使用http,不使用https。https有的时候返回内容读取后不是网页的html内容。
html = response.read()
response是一个类文件对象,通过read()读取,返回内容的编码格式是bytes类型。
python一般操作的都是字符串,将读取内容使用decode()进行编码。html = resoonse.read().decode('utf-8')
decode('utf-8')设置编码格式为utf-8。这个编码是根据原网页的编码格式决定的。
decode()默认的编码格式为utf-8。
如果原网页的编码格式为gb2312,使用gbk编码格式也可以,引文gbk包含gbk2312。with open('baidu.html',mode='w',encoding='utf-8') as f:
保存文件时,要指定编码格式。有时因为平台的不同,默认保存文件的编码格式不同。