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 相关文章推荐
Python3.2中的字符串函数学习总结
Apr 23 Python
Python中for循环控制语句用法实例
Jun 02 Python
Python网络爬虫神器PyQuery的基本使用教程
Feb 03 Python
python去除拼音声调字母,替换为字母的方法
Nov 28 Python
python3学生名片管理v2.0版
Nov 29 Python
python 与服务器的共享文件夹交互方法
Dec 27 Python
详解Django-restframework 之频率源码分析
Feb 27 Python
Python时间和字符串转换操作实例分析
Mar 16 Python
余弦相似性计算及python代码实现过程解析
Sep 18 Python
Python for循环通过序列索引迭代过程解析
Feb 07 Python
使用Tensorflow-GPU禁用GPU设置(CPU与GPU速度对比)
Jun 30 Python
Jupyter Notebook内使用argparse报错的解决方案
Jun 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设计模式之装饰者模式
2012/02/29 PHP
浅析get与post的一些特殊情况
2014/07/28 PHP
浅谈PHP发送HTTP请求的几种方式
2017/07/25 PHP
JS数组的赋值介绍
2014/03/10 Javascript
网页运行时提示对象不支持abigimage属性或方法
2014/08/10 Javascript
jQuery实现冻结表头的方法
2015/03/09 Javascript
AngularJS 单元测试(一)详解
2016/09/21 Javascript
vue 打包后的文件部署到express服务器上的方法
2017/08/09 Javascript
VUE中的无限循环代码解析
2017/09/22 Javascript
Vue的属性、方法、生命周期实例代码详解
2019/09/17 Javascript
浅谈python jieba分词模块的基本用法
2017/11/09 Python
为什么选择python编程语言入门黑客攻防 给你几个理由!
2018/02/02 Python
基于Django框架利用Ajax实现点赞功能实例代码
2018/08/19 Python
python 执行文件时额外参数获取的实例
2018/12/18 Python
PyTorch之图像和Tensor填充的实例
2019/08/18 Python
python处理excel绘制雷达图
2019/10/18 Python
后端开发使用pycharm的技巧(推荐)
2020/03/27 Python
如何更换python默认编辑器的背景色
2020/08/10 Python
Python实现Word文档转换Markdown的示例
2020/12/22 Python
HTML5+CSS3 实现灵动的动画 TAB 切换效果(DEMO)
2017/09/15 HTML / CSS
编写一子程序,将一链表倒序,即使链表表尾变表头,表头变表尾
2016/02/10 面试题
软件测试工程师结构化面试题库
2016/11/23 面试题
电脑教师的教学自我评价
2013/11/26 职场文书
事业单位竞聘上岗实施方案
2014/03/28 职场文书
我的长生果教学反思
2014/04/28 职场文书
安全负责人任命书
2014/06/06 职场文书
会计试用期自我评价
2014/09/19 职场文书
2014县委书记四风对照检查材料思想汇报
2014/09/21 职场文书
医院营销工作计划
2015/01/16 职场文书
2015年个人思想总结
2015/03/09 职场文书
幼儿园大班教师评语
2019/06/21 职场文书
基于Python实现的购物商城管理系统
2021/04/27 Python
css3 利用transform-origin 实现圆点分布在大圆上布局及旋转特效
2021/04/29 HTML / CSS
如何利用Matlab制作一款真正的拼图小游戏
2021/05/11 Python
如何使用PyCharm及常用配置详解
2021/06/03 Python
python利用pandas分析学生期末成绩实例代码
2021/07/09 Python