经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
Python urllib 入门使用详细教程
来源:jb51  时间:2022/11/19 17:13:04  对本文有异议

一、简介

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

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

二、 request 模块

1、urlopen:打开一个指定 URL,然后使用 read() 获取网页的 HTML 实体代码。

  1. # 使用 urllib
  2. import urllib.request
  3.  
  4. # 1、定义一个 url
  5. url = 'http://www.baidu.com'
  6.  
  7. # 2、模拟浏览器向服务器发送请求
  8. response = urllib.request.urlopen(url)
  9.  
  10. # 3、获取响应数据中的页面源码(注意:read() 返回的是字节形式的二进制数据,返回数据会被 b'xxx' 进行包裹)
  11. content = response.read()
  12.  
  13. # 4、输出二进制数据 content
  14. print(content)
  15. # 输出结果: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>'
  16.  
  17. # 5、将二进制数据转成字符串,这里需要网页对应的编码格式(例如:<meta http-equiv="Content-Type" content="text/html;charset=utf-8">),charset= 的就是编码格式 utf-8
  18. content = content.decode('utf-8')
  19.  
  20. # 6、输出字符串 content
  21. print(content)

2、response:响应的数据对象 HTTPResponse 类型

  1. # 使用 urllib
  2. import urllib.request
  3.  
  4. # 1、定义一个 url
  5. url = 'http://www.baidu.com'
  6.  
  7. # 2、模拟浏览器向服务器发送请求
  8. response = urllib.request.urlopen(url)
  9.  
  10. # response 是 http.client.HTTPResponse 类型
  11. print(type(response))
  12.  
  13. # read 方法是按照一个字节一个字节的去读取内容
  14. content = response.read()
  15. print(content)
  16.  
  17. # read 方法可以指定读取多少个字节
  18. content = response.read(50)
  19. print(content)
  20.  
  21. # 读取一行
  22. content = response.readline()
  23. print(content)
  24.  
  25. # 读取所有行
  26. content = response.readlines()
  27. print(content)
  28.  
  29. # 获取状态码
  30. print(response.getcode())
  31.  
  32. # 获取访问的链接地址
  33. print(response.geturl())
  34.  
  35. # 获取 headers
  36. print(response.getheaders())
  37.  

3、Request:自定义请求对象

  1. # 使用 urllib
  2. import urllib.request
  3.  
  4. # url 的组成
  5. # https://www.baidu.com/s?wd=123
  6.  
  7. # 协议 主机 端口号 路径 参数 锚点
  8. # http/https www.baidu.com 80 s wd #
  9. # http 80
  10. # https 443
  11. # mysql 3306
  12. # oracle 1521
  13. # redis 6379
  14. # mongdb 27017
  15.  
  16. # 1、定义一个 https 的 url
  17. url = 'https://www.baidu.com'
  18.  
  19. # 2、模拟浏览器向服务器发送请求
  20. response = urllib.request.urlopen(url)
  21.  
  22. # 3、获取内容字符串
  23. content = response.read().decode('utf-8')
  24.  
  25. # 4 会发现直接这么拿回来的数据不完整,这就是反扒的其中一种,代表给到服务器识别的信息不完整,比如 header 头里面的请求信息缺少。
  26. print(content)
  27.  
  28. # 解决方式:
  29.  
  30. # 定义 header
  31. headers = {
  32. # UA 最基本的防爬识别
  33. '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'
  34. }
  35.  
  36. # 1、定义一个 https 的 url
  37. url = 'https://www.baidu.com'
  38.  
  39. # 2、定义一个 Request 对象,urlopen 方法并不能直接带 header。
  40. # 细节:为什么这里需要写 url=url 而有的地方不需要?因为 Request 构造方法传参顺序问题 Request(url, data=None, headers={} ...)
  41. request = urllib.request.Request(url=url, headers=headers)
  42.  
  43. # 3、模拟浏览器向服务器发送请求
  44. response = urllib.request.urlopen(request)
  45.  
  46. # 3、获取内容字符串
  47. content = response.read().decode('utf-8')
  48.  
  49. # 4 输出
  50. print(content)
  51.  

4、urlretrieve:下载(例如:图片、视频、网页源码…)

  1. # 使用 urllib
  2. import urllib.request
  3.  
  4. # 下载网页
  5. url = 'http://www.baidu.com'
  6.  
  7. # 参数1:页面地址,参数2:文件名称(或路径与名称,例如:./test/baidu.html、baidu.html,不指定路径默认当前)
  8. urllib.request.urlretrieve(url, 'baidu.html')
  9.  
  10.  
  11. # 下载图片
  12. 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'
  13.  
  14. # 参数1:页面地址,参数2:文件名称(或路径与名称,例如:./test/baidu.html、baidu.html,不指定路径默认当前)
  15. urllib.request.urlretrieve(url, 'dzm.jpg')

二、 parse 模块

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

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

  1. # 使用 urllib
  2. import urllib.request
  3.  
  4. # 定义 header
  5. headers = {
  6. # UA 最基本的防爬识别
  7. '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'
  8. }
  9.  
  10. # 1、定义一个 https 的 url
  11.  
  12. # 这种中文写法会报错,因为 ascii 检索不到
  13. # url = 'https://www.baidu.com/s?wd=卡尔特斯CSDN'
  14.  
  15. # 也就是需要 `卡尔特斯CSDN` 变成 unicode 编码格式,例如这样:
  16. # url = 'https://www.baidu.com/s?wd=%E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN'
  17.  
  18. # 准备基础地址(不能整个链接去进行 quote 转换)(GET)
  19. url = 'https://www.baidu.com/s?wd='
  20.  
  21. # 通过 urllib.parse.quote() 进行转换
  22. wd = urllib.parse.quote('卡尔特斯CSDN')
  23. # print(wd) # %E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN
  24.  
  25. # 拼接起来
  26. url = url + wd
  27.  
  28. # 2、定义一个 Request 对象,urlopen 方法并不能直接带 header。
  29. # 细节:为什么这里需要写 url=url 而有的地方不需要?因为 Request 构造方法传参顺序问题 Request(url, data=None, headers={} ...)
  30. request = urllib.request.Request(url=url, headers=headers)
  31.  
  32. # 3、模拟浏览器向服务器发送请求
  33. response = urllib.request.urlopen(request)
  34.  
  35. # 3、获取内容字符串
  36. content = response.read().decode('utf-8')
  37.  
  38. # 4 输出
  39. print(content)
  40.  

2、urlencode:(GET)参数进行 unicode 编码

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

  1. # 使用 urllib
  2. import urllib.request
  3.  
  4. # 定义 header
  5. headers = {
  6. # UA 最基本的防爬识别
  7. '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'
  8. }
  9.  
  10. # 1、定义一个 https 的 url
  11.  
  12. # 这种中文写法会报错,因为 ascii 检索不到
  13. # url = 'https://www.baidu.com/s?wd=卡尔特斯CSDN&sex=男'
  14.  
  15. # 也就是需要 `卡尔特斯CSDN` 与 `男` 变成 unicode 编码格式,例如这样:
  16. # url = 'https://www.baidu.com/s?wd=%E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN&sex=%E7%94%B7'
  17.  
  18. # 准备基础地址(不能整个链接去进行 quote 转换)(GET)
  19. url = 'https://www.baidu.com/s?'
  20.  
  21. # 参数
  22. params = {
  23. 'wd': '卡尔特斯CSDN',
  24. 'sex': '男'
  25. }
  26.  
  27. # 通过 urllib.parse.urlencode() 进行转换(多个参数)
  28. str = urllib.parse.urlencode(params)
  29. # print(str) # wd=%E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN&sex=%E7%94%B7
  30.  
  31. # 通过 urllib.parse.quote() 进行转换(单个参数)
  32. # wd = urllib.parse.urlencode('卡尔特斯CSDN')
  33. # print(wd) # %E5%8D%A1%E5%B0%94%E7%89%B9%E6%96%AFCSDN
  34.  
  35. # 拼接起来
  36. url = url + str
  37.  
  38. # 2、定义一个 Request 对象,urlopen 方法并不能直接带 header。
  39. # 细节:为什么这里需要写 url=url 而有的地方不需要?因为 Request 构造方法传参顺序问题 Request(url, data=None, headers={} ...)
  40. request = urllib.request.Request(url=url, headers=headers)
  41.  
  42. # 3、模拟浏览器向服务器发送请求
  43. response = urllib.request.urlopen(request)
  44.  
  45. # 3、获取内容字符串
  46. content = response.read().decode('utf-8')
  47.  
  48. # 4 输出
  49. print(content)
  50.  

2、urlencode:(POST)参数进行 unicode 编码,附:Python爬虫Xpath定位数据的两种方法

  1. # 使用 urllib
  2. import urllib.request
  3. # 使用 json
  4. import json
  5.  
  6. # 定义 header
  7. headers = {
  8. # UA 最基本的防爬识别
  9. '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'
  10. }
  11.  
  12. # 请求地址(POST)
  13. url = 'https://fanyi.baidu.com/sug'
  14.  
  15. # 参数
  16. params = {
  17. 'kw': '名称'
  18. }
  19.  
  20. # post 请求,参数不能进行拼接,需放到请求对象指定的参数对象中
  21.  
  22. # 通过 urllib.parse.urlencode() 进行转换(多个参数)
  23. # str = urllib.parse.urlencode(params)
  24. # 直接使用转换的参数字符串会报错:POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.
  25. # request = urllib.request.Request(url=url, data=str, headers=headers)
  26.  
  27. # 上面直接使用参数字符串会报错,是因为 post 请求参数必须要要进行编码,指定编码格式
  28. data = urllib.parse.urlencode(params).encode('utf-8')
  29. # 模拟浏览器向服务器发送请求
  30. request = urllib.request.Request(url=url, data=data, headers=headers)
  31.  
  32. # 模拟浏览器向服务器发送请求
  33. response = urllib.request.urlopen(request)
  34.  
  35. # 获取内容字符串
  36. content = response.read().decode('utf-8')
  37.  
  38. # 将字符串转成 json
  39. obj = json.loads(content)
  40.  
  41. # 输出 json
  42. print(obj)
  43.  

三、 error 模块(URLError 与 HTTPError)

1、HTTPError 类是 URLError 类的子类。

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

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

  1. # 使用 urllib
  2. import urllib.request
  3. # 使用 json
  4. import json
  5.  
  6. # 定义 header
  7. headers = {
  8. # UA 最基本的防爬识别
  9. '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'
  10. }
  11.  
  12. # 请求地址(POST)
  13. url = 'https://fanyi.baidu.com/sug'
  14.  
  15. # 参数
  16. params = {
  17. 'kw': '名称'
  18. }
  19.  
  20. # post 请求,参数不能进行拼接,需放到请求对象指定的参数对象中
  21.  
  22. # 通过 urllib.parse.urlencode() 进行转换(多个参数)
  23. # str = urllib.parse.urlencode(params)
  24. # 直接使用转换的参数字符串会报错:POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.
  25. # request = urllib.request.Request(url=url, data=str, headers=headers)
  26.  
  27. # 上面直接使用参数字符串会报错,是因为 post 请求参数必须要要进行编码,指定编码格式
  28. data = urllib.parse.urlencode(params).encode('utf-8')
  29. # 模拟浏览器向服务器发送请求
  30. request = urllib.request.Request(url=url, data=data, headers=headers)
  31.  
  32. # 模拟浏览器向服务器发送请求
  33. response = urllib.request.urlopen(request)
  34.  
  35. # 获取内容字符串
  36. content = response.read().decode('utf-8')
  37.  
  38. # 将字符串转成 json
  39. obj = json.loads(content)
  40.  
  41. # 输出 json
  42. print(obj)
  43.  

四、Handler 处理器(IP 代理)

五、xppath 使用

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号