Python3中urllib模块的使用
转载自:https://www.cnblogs.com/php-linux/p/8365941.html
1.基本方法
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=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(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=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模块的使用的更多相关文章
- Python2和Python3中urllib库中urlencode的使用注意事项
前言 在Python中,我们通常使用urllib中的urlencode方法将字典编码,用于提交数据给url等操作,但是在Python2和Python3中urllib模块中所提供的urlencode的包 ...
- Python3:urllib模块的使用
Python3:urllib模块的使用1.基本方法 urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=N ...
- Python3中正则模块re.compile、re.match及re.search函数用法详解
Python3中正则模块re.compile.re.match及re.search函数用法 re模块 re.compile.re.match. re.search 正则匹配的时候,第一个字符是 r,表 ...
- python3中urllib库的request模块详解
刚刚接触爬虫,基础的东西得时时回顾才行,这么全面的帖子无论如何也得厚着脸皮转过来啊! 原帖地址:https://www.2cto.com/kf/201801/714859.html 什么是 Urlli ...
- 常见的爬虫分析库(1)-Python3中Urllib库基本使用
原文来自:https://www.cnblogs.com/0bug/p/8893677.html 什么是Urllib? Python内置的HTTP请求库 urllib.request ...
- Python3中Urllib库基本使用
什么是Urllib? Python内置的HTTP请求库 urllib.request 请求模块 urllib.error 异常处理模块 urllib.par ...
- python3中urllib的基本使用
urllib 在python3中,urllib和urllib2进行了合并,现在只有一个urllib模块,urllib和urllib2的中的内容整合进了urllib.request,urlparse整合 ...
- python3 中mlpy模块安装 出现 failed with error code 1的决绝办法(其他模块也可用本方法)
在python3 中安装其它模块时经常出现 failed with error code 1等状况,使的安装无法进行.而解决这个问题又非常麻烦. 接下来以mlpy为例,介绍一种解决此类安装问题的办法. ...
- Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)
urllib是python的一个获取url(Uniform Resource Locators,统一资源定址器)了,我们可以利用它来抓取远程的数据进行保存哦,下面整理了一些关于urllib使用中的一些 ...
随机推荐
- AIX修改密码
grid@DB01:/home/grid>su - oracleoracle's Password: 3004-303 There have been too many unsuccessful ...
- IR2104s半桥驱动使用经验
多次使用IR2104s,每次的调试都有种让人吐血的冲动.现在将使用过程遇到的错误给大家分享一下,方便大家找到思路. 一.自举电容部分(关键) 1.听说自举电路必须要安装场效应管,于是我在使用过程中,安 ...
- 谷歌AM HTML视频代码amp-video示例
ntroduction Use amp-video to embed videos into your AMP HTML files. Video source files must be serve ...
- MATLAB 通过对话框返回值选择下一步操作
学习来源:http://muchong.com/t-10428977-1-pid-1 Userchoice = questdlg(['您确定导入彩色图像?'],'提示','转为灰度图处理','展示彩色 ...
- mvc partialView+kendo window
在写mvc项目时,一个列表查询页面含有多个操作按钮及弹框操作.原本写在了一个view中,导致代码繁多复杂,难以维护,还有表单赋值清空.验证等麻烦. 因此改用kendo window +partialV ...
- Excel无法打开文件xxx.xlsx,因为文件格式或文件扩展名无效。请确定文件未损坏,并且文件扩展名与文件的格式匹配
office版本:2016 系统版本:win10 问题描述: 1.桌面新建excel表格后,打开时,提示“Excel无法打开文件xxx.xlsx,因为文件格式或文件扩展名无效.请确定文件未损坏,并且文 ...
- nist-sha
nist目前支持的sha运算,sha1系列,输出mac160bit. sha2系列,支持sha2-224,sha2-256,sha2-384,sha2-512,sha2-512/224,sha2-51 ...
- TypeError: '_io.TextIOWrapper' object does not support item assignment
纯小白 遇到的细节问题: 报错 一开始看到这个傻逼了 TypeError: '_io.TextIOWrapper' object does not support item assignment 其实 ...
- Hibernate的工作原理及使用的原因
一.工作原理: 1.读取并解析配置 2.读取并解析映射信息,创建Session Factory 3.打开Session 4.创建事务Transation 5.持久化操作 6.提交事务 7.关闭Sess ...
- Mysql 聚合函数返回NULL
[1]聚合函数返回NULL 当where条件不满足时,聚合函数sum().avg()的返回值为NULL. (1)源数据表 (2)如下SQL语句 SELECT sClass, COUNT(*) AS t ...