2025年6月4日 星期三 乙巳(蛇)年 三月初八 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

Python urllib 入门使用(步骤详细)

时间:02-28来源:作者:点击数:39

一、简介

urllib 库,它是 Python 内置的 HTTP 请求库,不需要额外安装即可使用,它包含四个模块:

  • `request` 请求模块,提供最基本的 `HTTP` 请求处理。
  • `parse` 工具模块,提供处理 `url` 的很多方法:拆分、解析、合并等等。
  • `error` 异常处理模块,如果出现请求错误,可以捕获这些错误,保证程序不会意外终止。
  • `robotparser` 模块,主要用来识别网站的 `robots.txt` 文件,判断哪些网站可以爬取,用的比较少。

二、 request 模块

1、urlopen:打开一个指定 URL,然后使用 read() 获取网页的 HTML 实体代码。
  • # 使用 urllib
  • import urllib.request
  • # 1、定义一个 url
  • url = 'http://www.baidu.com'
  • # 2、模拟浏览器向服务器发送请求
  • response = urllib.request.urlopen(url)
  • # 3、获取响应数据中的页面源码(注意:read() 返回的是字节形式的二进制数据,返回数据会被 b'xxx' 进行包裹)
  • content = response.read()
  • # 4、输出二进制数据 content
  • print(content)
  • # 输出结果:b'<html>\r\n<head>\r\n\t<script>\r\n\t\tlocation.replace(location.href.replace("https://","http://"));\r\n\t</script>\r\n</head>\r\n<body>\r\n\t<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>\r\n</body>\r\n</html>'
  • # 5、将二进制数据转成字符串,这里需要网页对应的编码格式(例如:<meta http-equiv="Content-Type" content="text/html;charset=utf-8">),charset= 的就是编码格式 utf-8
  • content = content.decode('utf-8')
  • # 6、输出字符串 content
  • print(content)
2、response:响应的数据对象 HTTPResponse 类型
  • # 使用 urllib
  • import urllib.request
  • # 1、定义一个 url
  • url = 'http://www.baidu.com'
  • # 2、模拟浏览器向服务器发送请求
  • response = urllib.request.urlopen(url)
  • # response 是 http.client.HTTPResponse 类型
  • print(type(response))
  • # read 方法是按照一个字节一个字节的去读取内容
  • content = response.read()
  • print(content)
  • # read 方法可以指定读取多少个字节
  • content = response.read(50)
  • print(content)
  • # 读取一行
  • content = response.readline()
  • print(content)
  • # 读取所有行
  • content = response.readlines()
  • print(content)
  • # 获取状态码
  • print(response.getcode())
  • # 获取访问的链接地址
  • print(response.geturl())
  • # 获取 headers
  • print(response.getheaders())
3、Request:自定义请求对象
  • # 使用 urllib
  • import urllib.request
  • # url 的组成
  • # https://www.baidu.com/s?wd=123
  • # 协议 主机 端口号 路径 参数 锚点
  • # http/https www.baidu.com 80 s wd #
  • # http 80
  • # https 443
  • # mysql 3306
  • # oracle 1521
  • # redis 6379
  • # mongdb 27017
  • # 1、定义一个 https 的 url
  • url = 'https://www.baidu.com'
  • # 2、模拟浏览器向服务器发送请求
  • response = urllib.request.urlopen(url)
  • # 3、获取内容字符串
  • content = response.read().decode('utf-8')
  • # 4 会发现直接这么拿回来的数据不完整,这就是反扒的其中一种,代表给到服务器识别的信息不完整,比如 header 头里面的请求信息缺少。
  • print(content)
  • # 解决方式:
  • # 定义 header
  • headers = {
  • # UA 最基本的防爬识别
  • 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
  • }
  • # 1、定义一个 https 的 url
  • url = 'https://www.baidu.com'
  • # 2、定义一个 Request 对象,urlopen 方法并不能直接带 header。
  • # 细节:为什么这里需要写 url=url 而有的地方不需要?因为 Request 构造方法传参顺序问题 Request(url, data=None, headers={} ...)
  • request = urllib.request.Request(url=url, headers=headers)
  • # 3、模拟浏览器向服务器发送请求
  • response = urllib.request.urlopen(request)
  • # 3、获取内容字符串
  • content = response.read().decode('utf-8')
  • # 4 输出
  • print(content)
4、urlretrieve:下载(例如:图片、视频、网页源码…)
  • # 使用 urllib
  • import urllib.request
  • # 下载网页
  • url = 'http://www.baidu.com'
  • # 参数1:页面地址,参数2:文件名称(或路径与名称,例如:./test/baidu.html、baidu.html,不指定路径默认当前)
  • urllib.request.urlretrieve(url, 'baidu.html')
  • # 下载图片
  • url = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F8%2F55402f62682e3.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1670904201&t=2dc001fbd959432efe8b8ee0792589ba'
  • # 参数1:页面地址,参数2:文件名称(或路径与名称,例如:./test/baidu.html、baidu.html,不指定路径默认当前)
  • urllib.request.urlretrieve(url, 'dzm.jpg')

二、 parse 模块

1、quote:(GET)参数进行 unicode 编码

quote 会对参数进行 unicode 编码,但是得一个一个参数的进行转换,在进行拼接,在多个参数时使用起来比较麻烦。

  • # 使用 urllib
  • import urllib.request
  • # 定义 header
  • headers = {
  • # UA 最基本的防爬识别
  • 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
  • }
  • # 1、定义一个 https 的 url
  • # 这种中文写法会报错,因为 ascii 检索不到
  • # url = 'https://www.baidu.com/s?wd=卡尔特斯CSDN'
  • # 也就是需要 `卡尔特斯CSDN` 变成 unicode 编码格式,例如这样:
  • # url = 'https://www.baidu.com/s?wd=%E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN'
  • # 准备基础地址(不能整个链接去进行 quote 转换)(GET)
  • url = 'https://www.baidu.com/s?wd='
  • # 通过 urllib.parse.quote() 进行转换
  • wd = urllib.parse.quote('卡尔特斯CSDN')
  • # print(wd) # %E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN
  • # 拼接起来
  • url = url + wd
  • # 2、定义一个 Request 对象,urlopen 方法并不能直接带 header。
  • # 细节:为什么这里需要写 url=url 而有的地方不需要?因为 Request 构造方法传参顺序问题 Request(url, data=None, headers={} ...)
  • request = urllib.request.Request(url=url, headers=headers)
  • # 3、模拟浏览器向服务器发送请求
  • response = urllib.request.urlopen(request)
  • # 3、获取内容字符串
  • content = response.read().decode('utf-8')
  • # 4 输出
  • print(content)
2、urlencode:(GET)参数进行 unicode 编码

urlencode 会对多个参数进行 unicode 编码。

  • # 使用 urllib
  • import urllib.request
  • # 定义 header
  • headers = {
  • # UA 最基本的防爬识别
  • 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
  • }
  • # 1、定义一个 https 的 url
  • # 这种中文写法会报错,因为 ascii 检索不到
  • # url = 'https://www.baidu.com/s?wd=卡尔特斯CSDN&sex=男'
  • # 也就是需要 `卡尔特斯CSDN` 与 `男` 变成 unicode 编码格式,例如这样:
  • # url = 'https://www.baidu.com/s?wd=%E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN&sex=%E7%94%B7'
  • # 准备基础地址(不能整个链接去进行 quote 转换)(GET)
  • url = 'https://www.baidu.com/s?'
  • # 参数
  • params = {
  • 'wd': '卡尔特斯CSDN',
  • 'sex': '男'
  • }
  • # 通过 urllib.parse.urlencode() 进行转换(多个参数)
  • str = urllib.parse.urlencode(params)
  • # print(str) # wd=%E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN&sex=%E7%94%B7
  • # 通过 urllib.parse.quote() 进行转换(单个参数)
  • # wd = urllib.parse.urlencode('卡尔特斯CSDN')
  • # print(wd) # %E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN
  • # 拼接起来
  • url = url + str
  • # 2、定义一个 Request 对象,urlopen 方法并不能直接带 header。
  • # 细节:为什么这里需要写 url=url 而有的地方不需要?因为 Request 构造方法传参顺序问题 Request(url, data=None, headers={} ...)
  • request = urllib.request.Request(url=url, headers=headers)
  • # 3、模拟浏览器向服务器发送请求
  • response = urllib.request.urlopen(request)
  • # 3、获取内容字符串
  • content = response.read().decode('utf-8')
  • # 4 输出
  • print(content)
2、urlencode:(POST)参数进行 unicode 编码,附:简单防爬处理
  • # 使用 urllib
  • import urllib.request
  • # 使用 json
  • import json
  • # 定义 header
  • headers = {
  • # UA 最基本的防爬识别
  • 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
  • }
  • # 请求地址(POST)
  • url = 'https://fanyi.baidu.com/sug'
  • # 参数
  • params = {
  • 'kw': '名称'
  • }
  • # post 请求,参数不能进行拼接,需放到请求对象指定的参数对象中
  • # 通过 urllib.parse.urlencode() 进行转换(多个参数)
  • # str = urllib.parse.urlencode(params)
  • # 直接使用转换的参数字符串会报错:POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.
  • # request = urllib.request.Request(url=url, data=str, headers=headers)
  • # 上面直接使用参数字符串会报错,是因为 post 请求参数必须要要进行编码,指定编码格式
  • data = urllib.parse.urlencode(params).encode('utf-8')
  • # 模拟浏览器向服务器发送请求
  • request = urllib.request.Request(url=url, data=data, headers=headers)
  • # 模拟浏览器向服务器发送请求
  • response = urllib.request.urlopen(request)
  • # 获取内容字符串
  • content = response.read().decode('utf-8')
  • # 将字符串转成 json
  • obj = json.loads(content)
  • # 输出 json
  • print(obj)

三、 error 模块(URLError 与 HTTPError

1、HTTPError 类是 URLError 类的子类。

2、导入包分别是:urllib.error.URLErrorurllib.error.HTTPError

3、通过 urllib 发送请求的时候,有可能发送失败,可以通过 try-except 进行异常捕获,异常有两类:URLError 与 HTTPError 类。

  • # 使用 urllib
  • import urllib.request
  • import urllib.error
  • # 定义 header
  • headers = {
  • # UA 最基本的防爬识别
  • 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
  • }
  • # 1、定义一个 https 的 url
  • # url = 'https://www.baidu.com/s?wd='
  • # 故意将参数或路径写错(会报错:urllib.error.HTTPError )
  • # url = 'https://www.baidu.com/s11111?wd='
  • # 故意将域名写错(会报错:urllib.error.URLError )
  • url = 'https://www.baidu111111.com/s?wd='
  • # 通过 urllib.parse.quote() 进行转换
  • wd = urllib.parse.quote('卡尔特斯CSDN')
  • # 拼接起来
  • url = url + wd
  • # 使用 try-except 出来异常
  • try:
  • # 2、定义一个 Request 对象,urlopen 方法并不能直接带 header
  • request = urllib.request.Request(url=url, headers=headers)
  • # 3、模拟浏览器向服务器发送请求
  • response = urllib.request.urlopen(request)
  • # 因为故意写错链接报错:urllib.error.HTTPError: HTTP Error 404: Not Found
  • # 3、获取内容字符串
  • content = response.read().decode('utf-8')
  • # 4 输出
  • print(content)
  • except urllib.error.HTTPError:
  • print('urllib.error.HTTPError 系统正在升级....')
  • except urllib.error.URLError:
  • print('urllib.error.URLError 系统正在升级....')

四、Handler 处理器(IP 代理)

五、xppath 使用

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门