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 相关文章推荐
PHP魔术方法__ISSET、__UNSET使用实例
Nov 25 Python
Python字符串处理之count()方法的使用
May 18 Python
Python的自动化部署模块Fabric的安装及使用指南
Jan 19 Python
TensorFlow模型保存/载入的两种方法
Mar 08 Python
Python基于多线程操作数据库相关问题分析
Jul 11 Python
numpy中loadtxt 的用法详解
Aug 03 Python
python/sympy求解矩阵方程的方法
Nov 08 Python
Pycharm取消py脚本中SQL识别的方法
Nov 29 Python
python科学计算之numpy——ufunc函数用法
Nov 25 Python
python 多进程队列数据处理详解
Dec 23 Python
pyftplib中文乱码问题解决方案
Jan 11 Python
python实现快速文件格式批量转换的方法
Oct 16 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数组函数序列 之array_count_values() 统计数组中所有值出现的次数函数
2011/10/29 PHP
解决phpmyadmin中缺少mysqli扩展问题的方法
2013/05/06 PHP
PHP模板解析类实例
2015/07/09 PHP
php高性能日志系统 seaslog 的安装与使用方法分析
2020/02/29 PHP
再谈ie和firefox下的document.all属性
2009/10/21 Javascript
JavaScript访问样式表代码
2010/10/15 Javascript
javascript实现数字验证码的简单实例
2014/02/10 Javascript
javascript实现tab切换特效
2015/11/12 Javascript
JavaScript面向对象程序设计教程
2016/03/29 Javascript
Jquery轮播效果实现过程解析
2016/03/30 Javascript
jQuery基于$.ajax设置移动端click超时处理方法
2016/05/14 Javascript
解决jQuery ajax动态新增节点无法触发点击事件的问题
2017/05/24 jQuery
jQuery实现的简单无刷新评论功能示例
2017/11/08 jQuery
常用的 JS 排序算法 整理版
2018/04/05 Javascript
为什么说JavaScript预解释是一种毫无节操的机制详析
2018/11/18 Javascript
详解JavaScript 的变量
2019/03/08 Javascript
Vue编写可显示周和月模式的日历 Vue自定义日历内容的显示
2019/06/26 Javascript
javascript设计模式 ? 中介者模式原理与用法实例分析
2020/04/20 Javascript
Vuex实现简单购物车
2021/01/10 Vue.js
python中的break、continue、exit()、pass全面解析
2017/08/05 Python
Python实现k-means算法
2018/02/23 Python
python实现机器学习之元线性回归
2018/09/06 Python
使用WingPro 7 设置Python路径的方法
2019/07/24 Python
python 字典有序并写入json文件过程解析
2019/09/30 Python
python 解决print数组/矩阵无法完整输出的问题
2020/02/19 Python
Python HTMLTestRunner测试报告view按钮失效解决方案
2020/05/25 Python
opencv 形态学变换(开运算,闭运算,梯度运算)
2020/07/07 Python
波兰最大的儿童服装连锁店之一:5.10.15.
2018/02/11 全球购物
LG西班牙网上商店:Tienda LG Online Es
2019/07/30 全球购物
String和StringBuffer的区别
2015/08/13 面试题
业绩考核岗位职责
2014/02/01 职场文书
团拜会策划方案
2014/06/07 职场文书
2016小学优秀教师先进事迹材料
2016/02/26 职场文书
大学生军训心得体会5篇
2019/08/15 职场文书
七年级作文之关于奶奶
2019/10/29 职场文书
能用CSS实现的就不要麻烦JavaScript了
2021/10/05 HTML / CSS