转载自:https://www.cnblogs.com/php-linux/p/8365941.html

1.基本方法

urllib.request.urlopen(urldata=None, [timeout, ]*cafile=Nonecapath=Nonecadefault=Falsecontext=None)

-         url:  需要打开的网址

-         data:Post提交的数据

-         timeout:设置网站的访问超时时间

直接用urllib.request模块的urlopen()获取页面,page的数据格式为bytes类型,需要decode()解码,转换成str类型。

1 from urllib import request
2 response = request.urlopen(r'http://python.org/') # <http.client.HTTPResponse object at 0x00000000048BC908> HTTPResponse类型
3 page = response.read()
4 page = page.decode('utf-8')

urlopen返回对象提供方法:

-         read() , readline() ,readlines() , fileno() , close() :对HTTPResponse类型数据进行操作

-         info():返回HTTPMessage对象,表示远程服务器返回的头信息

-         getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到

-         geturl():返回请求的url

2.使用Request

urllib.request.Request(url, data=None, headers={}, method=None)

使用request()来包装请求,再通过urlopen()获取页面。

 1 url = r'http://www.lagou.com/zhaopin/Python/?labelWords=label'
2 headers = {
3 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
4 r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
5 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
6 'Connection': 'keep-alive'
7 }
8 req = request.Request(url, headers=headers)
9 page = request.urlopen(req).read()
10 page = page.decode('utf-8')

用来包装头部的数据:

-         User-Agent :这个头部可以携带如下几条信息:浏览器名和版本号、操作系统名和版本号、默认语言

-         Referer:可以用来防止盗链,有一些网站图片显示来源http://***.com,就是检查Referer来鉴定的

-         Connection:表示连接状态,记录Session的状态。

3.Post数据

urllib.request.urlopen(urldata=None, [timeout, ]*cafile=Nonecapath=Nonecadefault=Falsecontext=None)

urlopen()的data参数默认为None,当data参数不为空的时候,urlopen()提交方式为Post。

 1 from urllib import request, parse
2 url = r'http://www.lagou.com/jobs/positionAjax.json?'
3 headers = {
4 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
5 r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
6 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
7 'Connection': 'keep-alive'
8 }
9 data = {
10 'first': 'true',
11 'pn': 1,
12 'kd': 'Python'
13 }
14 data = parse.urlencode(data).encode('utf-8')
15 req = request.Request(url, headers=headers, data=data)
16 page = request.urlopen(req).read()
17 page = page.decode('utf-8')

urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None)

urlencode()主要作用就是将url附上要提交的数据。

1 data = {
2 'first': 'true',
3 'pn': 1,
4 'kd': 'Python'
5 }
6 data = parse.urlencode(data).encode('utf-8')

经过urlencode()转换后的data数据为?first=true?pn=1?kd=Python,最后提交的url为

http://www.lagou.com/jobs/positionAjax.json?first=true?pn=1?kd=Python

Post的数据必须是bytes或者iterable of bytes,不能是str,因此需要进行encode()编码

1 page = request.urlopen(req, data=data).read()

当然,也可以把data的数据封装在urlopen()参数中

4.异常处理

 1 def get_page(url):
2 headers = {
3 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
4 r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
5 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
6 'Connection': 'keep-alive'
7 }
8 data = {
9 'first': 'true',
10 'pn': 1,
11 'kd': 'Python'
12 }
13 data = parse.urlencode(data).encode('utf-8')
14 req = request.Request(url, headers=headers)
15 try:
16 page = request.urlopen(req, data=data).read()
17 page = page.decode('utf-8')
18 except error.HTTPError as e:
19 print(e.code())
20 print(e.read().decode('utf-8'))
21 return page

5、使用代理

urllib.request.ProxyHandler(proxies=None)

当需要抓取的网站设置了访问限制,这时就需要用到代理来抓取数据。

 1 data = {
2 'first': 'true',
3 'pn': 1,
4 'kd': 'Python'
5 }
6 proxy = request.ProxyHandler({'http': '5.22.195.215:80'}) # 设置proxy
7 opener = request.build_opener(proxy) # 挂载opener
8 request.install_opener(opener) # 安装opener
9 data = parse.urlencode(data).encode('utf-8')
10 page = opener.open(url, data).read()
11 page = page.decode('utf-8')
12 return page

Python3中urllib模块的使用的更多相关文章

  1. Python2和Python3中urllib库中urlencode的使用注意事项

    前言 在Python中,我们通常使用urllib中的urlencode方法将字典编码,用于提交数据给url等操作,但是在Python2和Python3中urllib模块中所提供的urlencode的包 ...

  2. Python3:urllib模块的使用

    Python3:urllib模块的使用1.基本方法 urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=N ...

  3. Python3中正则模块re.compile、re.match及re.search函数用法详解

    Python3中正则模块re.compile.re.match及re.search函数用法 re模块 re.compile.re.match. re.search 正则匹配的时候,第一个字符是 r,表 ...

  4. python3中urllib库的request模块详解

    刚刚接触爬虫,基础的东西得时时回顾才行,这么全面的帖子无论如何也得厚着脸皮转过来啊! 原帖地址:https://www.2cto.com/kf/201801/714859.html 什么是 Urlli ...

  5. 常见的爬虫分析库(1)-Python3中Urllib库基本使用

    原文来自:https://www.cnblogs.com/0bug/p/8893677.html 什么是Urllib? Python内置的HTTP请求库 urllib.request          ...

  6. Python3中Urllib库基本使用

    什么是Urllib? Python内置的HTTP请求库 urllib.request          请求模块 urllib.error              异常处理模块 urllib.par ...

  7. python3中urllib的基本使用

    urllib 在python3中,urllib和urllib2进行了合并,现在只有一个urllib模块,urllib和urllib2的中的内容整合进了urllib.request,urlparse整合 ...

  8. python3 中mlpy模块安装 出现 failed with error code 1的决绝办法(其他模块也可用本方法)

    在python3 中安装其它模块时经常出现 failed with error code 1等状况,使的安装无法进行.而解决这个问题又非常麻烦. 接下来以mlpy为例,介绍一种解决此类安装问题的办法. ...

  9. Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)

    urllib是python的一个获取url(Uniform Resource Locators,统一资源定址器)了,我们可以利用它来抓取远程的数据进行保存哦,下面整理了一些关于urllib使用中的一些 ...

随机推荐

  1. navicat 远程访问mariadb失败,修改配置如下

    1.首先配置允许访问的用户,采用授权的方式给用户权限 GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'IDENTIFIED BY '121212' WITH GRAN ...

  2. 在Ubuntu中,vi命令编辑异常

    在Ubuntu中,进入vi命令的编辑模式,发现按方向键不能移动光标,而是会输出ABCD,以及退格键也不能正常删除字符.这是由于Ubuntu预装的是vim-tiny,而我们需要使用的是vim-full, ...

  3. 【JavaScript】第8章读书笔记

    本章常用的DOM方法 切记,页面的逻辑是:创建新的元素,给新的元素创建内容,通过appendChild把新元素的内容插入到新元素节点中:通过appendChild把新元素插入到已有元素节点中 书上的老 ...

  4. UnityWebRequest http post json通信

    unity3d 提供了一个用于http通信的类叫:UnityWebRequest,它是www的替代者,所以建议使用这个类.我们这个例子以json格式与服务器通信.这里使用的json组件是:Newton ...

  5. 2017-2018_OCR_papers汇总

    2017-2018_OCR_papers 1. 简单背景 基于深度的OCR方法的发展历程 近年来OCR发展热点与趋势 检测方法按照主题进行分类 2. ECCV + CVPR + ICCV +AAAI ...

  6. wm_concat函数的排序问题

    wm_concat在行转列的时候非常有用,但在行转列的过程中的排序问题常常难以控制. 可见下面例子: 准备测试表: drop table t; create table t (n number,m n ...

  7. shell里连接数据库,将结果输出到变量

    result=$(sqlplus -s 'ccc/ccc@21.96.34.34:1521'<<EOF ..... EOF )

  8. 多个for循环嵌套会影响速度

    在复现Meta-SR的过程中,发现如果嵌套多个for 循环会使速度过慢.这是下面实验得出的结论: import time t1 = time.time() a = range(3000) b = ra ...

  9. 20175208 实验二 《Java面向对象程序设计》实验报告

    一.实验报告封面 课程:Java程序设计  班级:1752班  姓名:张家华  学号:20175208 指导教师:娄嘉鹏  实验日期:2019年4月09日~2019年4月18日 实验序号:实验二 实验 ...

  10. kibana查询语法 使用教程

    1. 使用双引号包起来作为一个短语搜索: "like Gecko" 2. ? 匹配单个字符; * 匹配0到多个字符 例如:kiba?a, el*search ? * 不能用作第一个 ...