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聊天程序实例代码分享
Nov 18 Python
Python闭包的两个注意事项(推荐)
Mar 20 Python
使用python爬虫实现网络股票信息爬取的demo
Jan 05 Python
python 编码规范整理
May 05 Python
读取json格式为DataFrame(可转为.csv)的实例讲解
Jun 05 Python
Linux下python与C++使用dlib实现人脸检测
Jun 29 Python
基于python的列表list和集合set操作
Nov 24 Python
使用python-Jenkins批量创建及修改jobs操作
May 12 Python
Python判断远程服务器上Excel文件是否被人打开的方法
Jul 13 Python
Python DES加密实现原理及实例解析
Jul 17 Python
如何利用Matlab制作一款真正的拼图小游戏
May 11 Python
python3+PyQt5+Qt Designer实现界面可视化
Jun 10 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
thinkphp文件引用与分支结构用法实例
2014/11/26 PHP
PHP文字转图片功能原理与实现方法分析
2017/08/31 PHP
PHP单例模式数据库连接类与页面静态化实现方法
2019/03/20 PHP
js实现的网站首页随机公告随机公告
2007/03/14 Javascript
js chrome浏览器判断代码
2010/03/28 Javascript
js模仿hover的具体实现代码
2013/12/30 Javascript
基于Arcgis for javascript实现百度地图ABCD marker的效果
2015/09/12 Javascript
vue.js入门教程之计算属性
2016/09/01 Javascript
angular十大常见问题
2017/03/07 Javascript
Nodejs之http的表单提交
2017/07/07 NodeJs
深入理解React中何时使用箭头函数
2017/08/23 Javascript
浅谈Node.js CVE-2017-14849 漏洞分析(详细步骤)
2017/11/10 Javascript
jQuery中元素选择器(element)简单用法示例
2018/05/14 jQuery
Vue插件打包与发布的方法示例
2018/08/20 Javascript
在vue中安装使用vux的教程详解
2018/09/16 Javascript
javascript实现滚动条效果
2020/03/24 Javascript
Vue-cli assets SubDirectory及PublicPath区别详解
2020/08/18 Javascript
[01:01:18]DOTA2上海特级锦标赛主赛事日 - 2 败者组第二轮#2COL VS LGD
2016/03/03 DOTA
python3实现读取chrome浏览器cookie
2016/06/19 Python
python实现简单中文词频统计示例
2017/11/08 Python
Python实现判断字符串中包含某个字符的判断函数示例
2018/01/08 Python
python实现linux下抓包并存库功能
2018/07/18 Python
python实现决策树分类
2018/08/30 Python
Python爬虫动态ip代理防止被封的方法
2019/07/07 Python
Python爬虫学习之翻译小程序
2019/07/30 Python
在python3中使用shuffle函数要注意的地方
2020/02/28 Python
tensorflow下的图片标准化函数per_image_standardization用法
2020/06/30 Python
Pygame框架实现飞机大战
2020/08/07 Python
Pycharm 解决自动格式化冲突的设置操作
2021/01/15 Python
HTML5的Geolocation地理位置定位API使用教程
2016/05/12 HTML / CSS
店长岗位的工作内容
2013/11/12 职场文书
职称评定个人总结
2015/03/05 职场文书
保险公司岗前培训工作总结
2015/10/24 职场文书
学习党史心得体会2016
2016/01/23 职场文书
HTML常用标签超详细整理
2022/03/19 HTML / CSS
Python之matplotlib绘制饼图
2022/04/13 Python