一、函数功能
urllib.request 定义了一些打开 URL 的函数和类,包含授权验证、重定向、浏览器 cookies等,可以模拟浏览器的一个请求发起过程,我们可以利用urllib.request 的 urlopen 方法实现对目标URL的访问。
二、语法格式
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
参数介绍
- url:url 地址
- data:发送到服务器的其他数据对象,默认为 None
- timeout:设置访问超时时间
- cafile、capath:cafile 为 CA 证书, capath 为 CA 证书的路径,使用 HTTPS 需要用到
- cadefault:已经被弃用
- context:ssl.SSLContext类型,用来指定 SSL 设置(很少用)
三、实例
直接用urllib.request模块的urlopen()获取页面,page的数据格式为bytes类型,需要转换成str类型(两种方法比较常用,一是decode(),二是类型转换函数str())
# encoding : utf-8
"""
@author: LY
@contact: 13904442175@163.com
@software: PyCharm
@file: urlopen_code.py
"""
import urllib.request
def load_data():
url = "http://www.baidu.com/"
# get的请求
# http请求
# response:http相应的对象
response = urllib.request.urlopen(url)
print(response)
# 读取内容 bytes类型
data = response.read()
print(data)
# 将文件获取的内容转换成字符串
str_data = data.decode("utf-8")
print(str_data)
# 将数据写入文件
with open("baidu.html", "w", encoding="utf-8")as f:
f.write(str_data)
# 将字符串类型转换成bytes
str_name = "baidu"
bytes_name = str_name.encode("utf-8")
print(bytes_name)
# python爬取的类型:str bytes
# 如果爬取回来的是bytes类型:但是你写入的时候需要字符串 decode("utf-8")
# 如果爬取过来的是str类型:但你要写入的是bytes类型 encode(""utf-8")
load_data()