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中的XML 工具
Apr 13 Python
九步学会Python装饰器
May 09 Python
简单的Apache+FastCGI+Django配置指南
Jul 22 Python
pyenv命令管理多个Python版本
Mar 26 Python
Python实现PS图像抽象画风效果的方法
Jan 23 Python
Python实现的本地文件搜索功能示例【测试可用】
May 30 Python
Windows系统下PhantomJS的安装和基本用法
Oct 21 Python
对numpy下的轴交换transpose和swapaxes的示例解读
Jun 26 Python
基于 Django 的手机管理系统实现过程详解
Aug 16 Python
解决Python命令行下退格,删除,方向键乱码(亲测有效)
Jan 16 Python
Python实现加密的RAR文件解压的方法(密码已知)
Sep 11 Python
python 实现批量图片识别并翻译
Nov 02 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批量上传图片的具体实现方法介绍.
2014/02/26 PHP
ThinkPHP多语言支持与多模板支持概述
2014/08/22 PHP
thinkphp中多表查询中防止数据重复的sql语句(必看)
2016/09/22 PHP
PHP实现的贪婪算法实例
2017/10/17 PHP
自动检查并替换文本框内的字符
2006/06/30 Javascript
JQuery 操作/获取table具体代码
2013/06/13 Javascript
js函数返回多个返回值的示例代码
2013/11/05 Javascript
jQuery实现的图片分组切换焦点图插件
2015/01/06 Javascript
jQuery实现鼠标经过图片变亮其他变暗效果
2015/05/08 Javascript
原生js实现返回顶部缓冲效果
2017/01/18 Javascript
angularjs+bootstrap菜单的使用示例代码
2017/03/07 Javascript
基于jQuery的左滑出现删除按钮的示例
2017/08/29 jQuery
微信小程序request请求后台接口php的实例详解
2017/09/20 Javascript
谈谈JS中的!!
2017/12/07 Javascript
JS运动特效之链式运动分析
2018/01/24 Javascript
node.js中express模块创建服务器和http模块客户端发请求
2019/03/06 Javascript
Vue 引入AMap高德地图的实现代码
2019/04/29 Javascript
vue增加强缓存和版本号的实现方法
2019/05/01 Javascript
何时/使用 Vue3 render 函数的教程详解
2020/07/25 Javascript
Python装饰器限制函数运行时间超时则退出执行
2019/04/09 Python
如何分离django中的媒体、静态文件和网页
2019/11/12 Python
自定义Django默认的sitemap站点地图样式
2020/03/04 Python
python实现猜单词游戏
2020/05/22 Python
Python Django搭建网站流程图解
2020/06/13 Python
最新版 Windows10上安装Python 3.8.5的步骤详解
2020/11/28 Python
AmazeUI 加载进度条的实现示例
2020/08/20 HTML / CSS
美国高级音响品牌:Master&Dynamic
2018/07/05 全球购物
印尼值得信赖的在线交易网站:Bukalapak
2019/03/11 全球购物
领导的自我鉴定
2013/12/28 职场文书
大学生个人事迹材料
2014/01/21 职场文书
企业军训感想
2014/02/07 职场文书
集团公司党的群众路线教育实践活动工作总结
2014/03/03 职场文书
《棉鞋里的阳光》教学反思
2014/04/24 职场文书
优秀应届本科生求职信
2014/07/19 职场文书
2019军训心得体会
2019/06/27 职场文书
Python基础之pandas数据合并
2021/04/27 Python