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


Posted in Python onSeptember 21, 2016

我们可以利用urllib来抓取远程的数据进行保存哦,以下是python3 抓取网页资源的多种方法,有需要的可以参考借鉴。

1、最简单

import urllib.request
response = urllib.request.urlopen('http://python.org/')
html = response.read()

2、使用 Request

import urllib.request
req = urllib.request.Request('http://python.org/')
response = urllib.request.urlopen(req)
the_page = response.read()

3、发送数据

#! /usr/bin/env python3
import urllib.parse
import urllib.request
url = 'http://localhost/login.php'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {
'act' : 'login',
'login[email]' : 'yzhang@i9i8.com',
'login[password]' : '123456'
}
data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data)
req.add_header('Referer', 'http://www.python.org/')
response = urllib.request.urlopen(req)
the_page = response.read()
print(the_page.decode("utf8"))

4、发送数据和header

#! /usr/bin/env python3
import urllib.parse
import urllib.request
url = 'http://localhost/login.php'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {
'act' : 'login',
'login[email]' : 'yzhang@i9i8.com',
'login[password]' : '123456'
}
headers = { 'User-Agent' : user_agent }
data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
the_page = response.read()
print(the_page.decode("utf8"))

5、http 错误

#! /usr/bin/env python3
import urllib.request
req = urllib.request.Request('https://3water.com ')
try:
urllib.request.urlopen(req)
except urllib.error.HTTPError as e:
print(e.code)
print(e.read().decode("utf8"))

6、异常处理1

#! /usr/bin/env python3
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request("https://3water.com /")
try:
response = urlopen(req)
except HTTPError as e:
print('The server couldn't fulfill the request.')
print('Error code: ', e.code)
except URLError as e:
print('We failed to reach a server.')
print('Reason: ', e.reason)
else:
print("good!")
print(response.read().decode("utf8"))

7、异常处理2

#! /usr/bin/env python3
from urllib.request import Request, urlopen
from urllib.error import URLError
req = Request("https://3water.com /")
try:
response = urlopen(req)
except URLError as e:
if hasattr(e, 'reason'):
print('We failed to reach a server.')
print('Reason: ', e.reason)
elif hasattr(e, 'code'):
print('The server couldn't fulfill the request.')
print('Error code: ', e.code)
else:
print("good!")
print(response.read().decode("utf8"))

8、HTTP 认证

#! /usr/bin/env python3
import urllib.request
# create a password manager
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url = "https://3water.com /"
password_mgr.add_password(None, top_level_url, 'rekfan', 'xxxxxx')
handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)
# use the opener to fetch a URL
a_url = "https://3water.com /"
x = opener.open(a_url)
print(x.read())
# Install the opener.
# Now all calls to urllib.request.urlopen use our opener.
urllib.request.install_opener(opener)
a = urllib.request.urlopen(a_url).read().decode('utf8')
print(a)

9、使用代理

#! /usr/bin/env python3
import urllib.request
proxy_support = urllib.request.ProxyHandler({'sock5': 'localhost:1080'})
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)

a = urllib.request.urlopen("https://3water.com ").read().decode("utf8")
print(a)

10、超时

#! /usr/bin/env python3
import socket
import urllib.request
# timeout in seconds
timeout = 2
socket.setdefaulttimeout(timeout)
# this call to urllib.request.urlopen now uses the default timeout
# we have set in the socket module
req = urllib.request.Request('https://3water.com /')
a = urllib.request.urlopen(req).read()
print(a)

总结

以上就是这篇文章的全部内容,希望本文的内容对大家学习或使用python能有所帮助,如果有疑问大家可以留言交流。

Python 相关文章推荐
python中二维阵列的变换实例
Oct 09 Python
Python实现信用卡系统(支持购物、转账、存取钱)
Jun 24 Python
关于Python中浮点数精度处理的技巧总结
Aug 10 Python
Python实现可自定义大小的截屏功能
Jan 20 Python
使用matplotlib画散点图的方法
May 25 Python
使用Python将Mysql的查询数据导出到文件的方法
Feb 25 Python
python查询文件夹下excel的sheet名代码实例
Apr 02 Python
Python3内置模块之base64编解码方法详解
Jul 13 Python
python使用百度文字识别功能方法详解
Jul 23 Python
pytorch中tensor张量数据类型的转化方式
Dec 31 Python
python实现将range()函数生成的数字存储在一个列表中
Apr 02 Python
Python os库常用操作代码汇总
Nov 03 Python
浅析Python中MySQLdb的事务处理功能
Sep 21 #Python
Python 爬虫学习笔记之多线程爬虫
Sep 21 #Python
Python 爬虫学习笔记之单线程爬虫
Sep 21 #Python
Python 爬虫学习笔记之正则表达式
Sep 21 #Python
Python简单实现安全开关文件的两种方式
Sep 19 #Python
Python打包可执行文件的方法详解
Sep 19 #Python
Python实现拷贝多个文件到同一目录的方法
Sep 19 #Python
You might like
PHP+Javascript实现在线拍照功能实例
2015/07/18 PHP
PHP手机号码及邮箱正则表达式实例解析
2020/07/11 PHP
高亮显示web页表格行的javascript代码
2010/11/19 Javascript
一些javascript一些题目的解析
2010/12/25 Javascript
用Mootools获得操作索引的两种方法分享
2011/12/12 Javascript
javascript获得网页窗口实际大小的示例代码
2013/09/21 Javascript
jQuery focus和blur事件的应用详解
2014/01/26 Javascript
jquery+css实现绚丽的横向二级下拉菜单-附源码下载
2015/08/23 Javascript
牛叉的Jquery——Jquery与DOM对象的互相转换及DOM的三种操作
2015/10/29 Javascript
JS中的forEach、$.each、map方法推荐
2016/04/05 Javascript
angularjs ui-router中路由的二级嵌套
2017/03/10 Javascript
js下载文件并修改文件名
2017/05/08 Javascript
javascript 玩转Date对象(实例讲解)
2017/07/11 Javascript
jQuery DOM节点的遍历方法小结
2017/08/15 jQuery
Vue中 v-if/v-show/插值表达式导致闪现的原因及解决办法
2018/10/12 Javascript
JavaScript变量提升和严格模式实例分析
2019/01/27 Javascript
BootstrapValidator实现表单验证功能
2019/11/08 Javascript
jquery使用echarts实现有向图可视化功能示例
2019/11/25 jQuery
js实现无缝轮播图
2020/03/09 Javascript
vue中实现图片压缩 file文件的方法
2020/05/28 Javascript
JQuery使用数组遍历跳出each循环
2020/09/01 jQuery
[01:15]《辉夜杯》北京网鱼队巡礼
2015/10/26 DOTA
对python numpy.array插入一行或一列的方法详解
2019/01/29 Python
python查找重复图片并删除(图片去重)
2019/07/16 Python
python os.path.isfile 的使用误区详解
2019/11/29 Python
Python 添加文件注释和函数注释操作
2020/08/09 Python
HTML5 Canvas API中drawImage()方法的使用实例
2016/03/25 HTML / CSS
世界上第一个水枕头:Mediflow
2018/12/06 全球购物
Perfume’s Club法国站:购买香水和化妆品
2019/05/02 全球购物
Hotels.com印度:酒店预订
2019/05/11 全球购物
六查六看剖析材料
2014/02/15 职场文书
机械制造专业毕业生求职信
2014/03/02 职场文书
2014年圣诞节促销方案
2014/03/14 职场文书
社区春季防火方案
2014/06/02 职场文书
群众路线个人整改方案
2014/10/25 职场文书
2016年端午节寄语
2015/12/04 职场文书