掌握函数urlopen()的用法

一、函数功能

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()

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值