python中urllib.request对象案例

刚刚接触爬虫,基础的东西得时时回顾才行,这么全面的帖子无论如何也得厚着脸皮转过来啊!

什么是 Urllib 库?

urllib 库 是 Python 内置的 HTTP 请求库。urllib 模块提供的上层接口,使访问 www 和 ftp 上的数据就像访问本地文件一样。

有以下几种模块:

1.urllib.request 请求模块

2. urllib.error 异常处理模块

3. urllib.parse url 解析模块

4. urllib.robotparser robots.txt 解析模块

Urllib 库下的几种模块基本使用如下:

urllib.request

关于 urllib.request: urllib.request 模块提供了最基本的构造 HTTP (或其他协议如 FTP)请求的方法,利用它可以模拟浏览器的一个请求发起过程。利用不同的协议去获取 URL 信息。它的某些接口能够处理基础认证 ( Basic Authenticaton) 、redirections (HTTP 重定向)、 Cookies (浏览器 Cookies)等情况。而这些接口是由 handlers 和 openers 对象提供的。

1.常用的方法有

  read()==读取文件内容
  geturl()==获取请求url
  getheaders()==获取http请求头信息
  getcode()==获取状态码
  readlines()==获取一行

2.案例

#coding=utf-8
#import urllib.request
#=========response方法使用
#read()==读取文件内容
#geturl()==获取请求url
#getheaders()==获取http请求头信息
#getcode()==获取状态码
#readlines()==获取一行
#url="http://www.baidu.com";
#response = urllib.request.urlopen(url);
#=====案例1
# str = response.read().decode();#这样通过decode转换为utf8
# with open("baidu.html","w",encoding="utf8") as fp:
#     fp.write(str);
#=====案例2通过字节流写=默认通过read读取的是字节流
# with open("bai.html","wb") as fp:
#     fp.write(response.read()); 
#==使用字节流读取存图片
# image_url='https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3772530225,1800402028&fm=26&gp=0.jpg';
# response = urllib.request.urlopen(image_url);
# with open("mv.jpg",'wb') as fp:
#     fp.write(response.read());
#案例3==使用内置函数读取图片
#image_url='https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3772530225,1800402028&fm=26&gp=0.jpg';
#urllib.request.urlretrieve(image_url,"chun.jpg"); 
原文地址:https://www.cnblogs.com/zh718594493/p/12391296.html