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爬虫框架Scrapy安装使用步骤
Apr 01 Python
Python yield 使用方法浅析
May 20 Python
python实现括号匹配的思路详解
Aug 23 Python
Python学习笔记之图片人脸检测识别实例教程
Mar 06 Python
python使用pymongo操作mongo的完整步骤
Apr 13 Python
Python读写文件基础知识点
Jun 10 Python
jenkins配置python脚本定时任务过程图解
Oct 29 Python
CentOS7下安装python3.6.8的教程详解
Jan 03 Python
Python SQLAlchemy库的使用方法
Oct 13 Python
Python 数据可视化之Matplotlib详解
Nov 02 Python
Python字符串的转义字符
Apr 07 Python
Python使用BeautifulSoup4修改网页内容
May 20 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
Yii中Model(模型)的创建及使用方法
2015/12/28 PHP
老生常谈PHP位运算的用途
2017/03/12 PHP
js客户端快捷键管理类的较完整实现和应用
2010/06/08 Javascript
Uglifyjs(JS代码优化工具)入门 安装使用
2020/04/13 Javascript
使用JavaScript动态设置样式实现代码及演示动画
2013/01/25 Javascript
js控制frameSet示例
2013/09/10 Javascript
用jquery统计子菜单的条数示例代码
2013/10/18 Javascript
利用cookie记住背景颜色示例代码
2013/11/04 Javascript
iframe子页面获取父页面元素的方法
2013/11/05 Javascript
jQuery根据ID获取input、checkbox、radio、select的示例
2014/08/11 Javascript
uploadify多文件上传参数设置技巧
2015/11/16 Javascript
通过JS获取Request.QueryString()参数的值实现方法
2016/09/27 Javascript
微信小程序 教程之模板
2016/10/18 Javascript
NodeJs的fs读写删除移动监听
2017/04/28 NodeJs
Javascript获取某个月的天数
2018/05/30 Javascript
[42:34]VP vs VG 2018国际邀请赛小组赛BO2 第一场 8.19
2018/08/21 DOTA
Python实现基于HTTP文件传输实例
2014/11/08 Python
在Python程序中实现分布式进程的教程
2015/04/28 Python
Python基于list的append和pop方法实现堆栈与队列功能示例
2017/07/24 Python
Python AES加密实例解析
2018/01/18 Python
Python给定一个句子倒序输出单词以及字母的方法
2018/12/20 Python
python 实现一次性在文件中写入多行的方法
2019/01/28 Python
Python 依赖库太多了该如何管理
2019/11/08 Python
python 实现多维数组转向量
2019/11/30 Python
pytorch 利用lstm做mnist手写数字识别分类的实例
2020/01/10 Python
TensorFlow 显存使用机制详解
2020/02/03 Python
深入了解NumPy 高级索引
2020/07/24 Python
python3.9.1环境安装的方法(图文)
2021/02/02 Python
html5 button autofocus 属性介绍及应用
2013/01/04 HTML / CSS
在HTML5中使用MathML数学公式的简单讲解
2016/02/19 HTML / CSS
娇韵诗Clarins意大利官方网站:法国天然护肤品牌
2020/03/11 全球购物
商务英语专业求职信范文
2014/01/28 职场文书
四风个人对照检查材料思想汇报
2014/09/25 职场文书
农业项目合作意向书
2015/05/08 职场文书
新员工辞职信范文
2015/05/12 职场文书
css position fixed 左右双定位的实现代码
2021/04/29 HTML / CSS