urllib基础-请求对象request 简单的案例-爬取百度首页

 1 from urllib import request
 2 '''
 3 爬取百度首页
 4 '''
 5 # 确定爬去目标
 6 base_url = 'http://www.baidu.com'
 7 
 8 # 发起http请求 返回一个类文件对象
 9 response = request.urlopen(url=base_url)
10 
11 # 获取相应内容
12 html = response.read()
13 
14 # 把bytes类型转换成utf-8编码的字符串类型
15 html = html.decode('utf-8')
16 
17 # 写入文件
18 with open('baidu.html','w',encoding='utf-8') as f:
19     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:
  保存文件时,要指定编码格式。有时因为平台的不同,默认保存文件的编码格式不同。