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 相关文章推荐
400多行Python代码实现了一个FTP服务器
May 10 Python
Python中使用PIL库实现图片高斯模糊实例
Feb 08 Python
以视频爬取实例讲解Python爬虫神器Beautiful Soup用法
Jan 20 Python
python爬虫之BeautifulSoup 使用select方法详解
Oct 23 Python
用Python进行简单图像识别(验证码)
Jan 19 Python
获取python文件扩展名和文件名方法
Feb 02 Python
详解Appium+Python之生成html测试报告
Jan 04 Python
解决pycharm回车之后不能换行或不能缩进的问题
Jan 16 Python
简单了解python PEP的一些知识
Jul 13 Python
python统计函数库scipy.stats的用法解析
Feb 25 Python
Python Tornado批量上传图片并显示功能
Mar 26 Python
python -v 报错问题的解决方法
Sep 15 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获取数组最后一个值的2种方法
2015/01/21 PHP
JavaScript 实现模态对话框 源代码大全
2009/05/02 Javascript
用js实现计算加载页面所用的时间
2010/04/02 Javascript
jQuery.each()用法分享
2012/07/31 Javascript
使用JavaScript 实现对象 匀速/变速运动的方法
2013/05/08 Javascript
JavaScript 链式结构序列化详解
2016/09/30 Javascript
JavaScript 实现 Tab 点击切换实例代码
2017/03/25 Javascript
AugularJS从入门到实践(必看篇)
2017/07/10 Javascript
微信小程序支付功能 php后台对接完整代码分享
2018/06/12 Javascript
vue项目首屏打开速度慢的解决方法
2019/03/31 Javascript
微信小程序表单验证插件WxValidate的二次封装功能(终极版)
2019/09/03 Javascript
详解ECMAScript2019/ES10新属性
2019/12/06 Javascript
vue实现折线图 可按时间查询
2020/08/21 Javascript
vue内置组件keep-alive事件动态缓存实例
2020/10/30 Javascript
Vue 防止短时间内连续点击后多次触发请求的操作
2020/11/11 Javascript
[07:12]2014DOTA2西雅图国际邀请赛 黑马Liquid专题采访
2014/07/12 DOTA
python抓取网页图片示例(python爬虫)
2014/04/27 Python
Django contenttypes 框架详解(小结)
2018/08/13 Python
python使用xlrd和xlwt读写Excel文件的实例代码
2018/09/05 Python
Python爬取成语接龙类网站
2018/10/19 Python
pyqt5 使用cv2 显示图片,摄像头的实例
2019/06/27 Python
python实现自动化上线脚本的示例
2019/07/01 Python
Python正则表达式急速入门(小结)
2019/12/16 Python
python pprint模块中print()和pprint()两者的区别
2020/02/10 Python
浅谈Python中range与Numpy中arange的比较
2020/03/11 Python
详解python日志输出使用配置文件格式
2021/02/10 Python
美国最大的宠物药店:1-800-PetMeds
2016/10/02 全球购物
adidas菲律宾官网:adidas PH
2020/02/07 全球购物
一道SQL面试题
2012/12/31 面试题
网络工程师个人的自我评价范文
2013/10/01 职场文书
物流专业大学生求职信范文
2013/10/28 职场文书
诉讼代理人授权委托书
2014/04/08 职场文书
个人投资合作协议书
2014/10/12 职场文书
干部个人考察材料
2014/12/24 职场文书
如何开发一个渐进式Web应用程序PWA
2021/05/10 Javascript
MySql 8.0及对应驱动包匹配的注意点说明
2021/06/23 MySQL