转载自: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. locust压测websocket协议

    Locust是以HTTP为主要目标构建的. 但是,通过编写触发器request_success和 request_failure事件的自定义客户端,可以轻松扩展到任何基于请求/响应的系统的负载测试 . ...

  2. mvc自定义分页(加页数的)(转)

    1.引言 在MVC开发中我们经常会对数据进行分页的展示.通过分页我们可以从服务端获取指定的数据来进行展示.这样既节约了数据库查询的时间也节约了网络传输的数据量.在MVC开发中使用的比较多的应该是MVC ...

  3. Linq To Object 函数介绍

    static void Main(string[] args) { #region Aggregate 把集合中的元素按照表达式依次执行 { IEnumerable<int> list = ...

  4. go basic

    go time and rand: package main import ( "fmt" "math/rand" "time" ) fun ...

  5. Oracle 体系结构chapter2

    前言:Oracle 体系结构其实就是指oracle 服务器的体系结构,数据库服务器主要由三个部分组成 管理数据库的各种软件工具(sqlplus,OEM等),实例(一组oracle 后台进程以及服务器中 ...

  6. PKCS RSA执行标准

    RSA是一种算法,但是,在相关应用的时候,还是需要有一些标准的.这就是pkcs.现在的各种程序中,基本都是遵循这个标准来使用RSA的.最近陆续读取RSA相关的内容进行学习. RSA官网:https:/ ...

  7. Xamarin.Forms + Prism,整理页面导航跳转流程

    3个Page,Page1 -> Page2 -> Page3 -> Page2 -> Page1. PageViewModel实现接口:INavigatingAware, IN ...

  8. redis 分页

    redis 分页 > rpush a (integer) > rpush a (integer) > rpush a (integer) > rpush a (integer) ...

  9. Python-----多线程threading用法

    threading模块是Python里面常用的线程模块,多线程处理任务对于提升效率非常重要,先说一下线程和进程的各种区别,如图 概括起来就是 IO密集型(不用CPU) 多线程计算密集型(用CPU) 多 ...

  10. 《CSS世界》读书笔记(十六)

    <!-- <CSS世界>张鑫旭著 --> line-height与“垂直居中” line-height 可以让单行或多行元素近似垂直居中,原因在于 CSS 中“行距的上下等分机 ...