Python爬虫教程002:urllib库基本使用

文章目录

    • [2.1 urllib基本使用](#2.1 urllib基本使用)
    • [2.2 urllib的1个类型6个方法](#2.2 urllib的1个类型6个方法)
    • [2.3 urllib下载](#2.3 urllib下载)

2.1 urllib基本使用

示例代码:

python 复制代码
# -*- coding: utf-8 -*-
# @Time: 2022/9/24 0024 9:47
# @Author: Wang
# @File: 01_urllib_基本使用.py

# 使用urllib来获取百度首页的源码
import urllib.request

# (1)定义一个url,就是你要访问的地址
url = 'http://www.baidu.com'

# (2)模拟浏览器向服务器发送请求
response = urllib.request.urlopen(url=url)

# (3)获取响应的页面源码
# read方法:返回的是字节形式的二进制数据
# 我们要将二进制的数据转换为字符串
# 二进制->字符串的动作:解码 decode('编码的格式')
content = response.read().decode('utf-8')

# (4)打印数据
print(content)

打印结果:

2.2 urllib的1个类型6个方法

python 复制代码
# -*- coding: utf-8 -*-
# @Time: 2022/9/24 0024 10:02
# @Author: Wang
# @File: 02_urllib_1个类型和6个方法.py

import urllib.request

url = 'http://www.baidu.com'

# 模拟浏览器向服务器发送请求
response = urllib.request.urlopen(url)

# 1个类型和6个方法
# response是HTTPResponse的类型
# print(type(response))

# 按照一个字节一个字节的去读
# content = response.read()
# print(content)

# 返回多少个字节
# content = response.read(5)
# print(content)

# 读取一行
# content = response.readline()
# print(content)

# 读取所有行
# content = response.readlines()
# print(content)

# 状态码
print(response.getcode())  # 200

# 请求url
print(response.geturl())  # http://www.baidu.com

# 状态信息
print(response.getheaders())

# 1个类型是HTTPResponse
# 6个方法 read readline readlines getcode geturl getheaders

2.3 urllib下载

下载网页

示例代码:

python 复制代码
import urllib.request

# 下载网页
url_page = 'http://www.baidu.com'

# url代表的是下载的路径 filename文件名
# 在python中,可以写变量的名字,也可以直接写值
urllib.request.urlretrieve(url_page, 'baidu.html')

运行结果:将爬取到的网页保存为baidu.html文件,可以直接通过浏览器打开,即是百度的首页。

下载图片

示例代码:

python 复制代码
# 下载图片
url_img = 'https://img2.baidu.com/it/u=1390544076,2637920000&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=625'

urllib.request.urlretrieve(url_img, 'lisa.jpg')

下载结果:

下载视频

python 复制代码
# 下载视频
url_vidio = 'https://vd2.bdstatic.com/mda-jmki3yf92d7w4ft9/v1-cae/sc/mda-jmki3yf92d7w4ft9.mp4?v_from_s=hkapp-haokan-hbf&auth_key=1664077962-0-0-93246b00edbdd7bda4482e4bbd5bc4d1&bcevod_channel=searchbox_feed&pd=1&cd=0&pt=3&logid=1362660174&vid=5104542693201134340&abtest=&klogid=1362660174'

urllib.request.urlretrieve(url_vidio, 'lisa.mp4')
相关推荐
ZhengEnCi1 小时前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 小时前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187912 小时前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L19 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅19 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅19 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L19 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅20 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L20 小时前
python的类&继承
python
Warson_L20 小时前
类型标注/type annotation
python