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 相关文章推荐
使用rst2pdf实现将sphinx生成PDF
Jun 07 Python
用python写一个windows下的定时关机脚本(推荐)
Mar 21 Python
python爬虫面试宝典(常见问题)
Mar 02 Python
详解Python 协程的详细用法使用和例子
Jun 15 Python
python按照多个条件排序的方法
Feb 08 Python
FFrpc python客户端lib使用解析
Aug 24 Python
详解一种用django_cache实现分布式锁的方式
Sep 01 Python
使用python脚本自动创建pip.ini配置文件代码实例
Sep 20 Python
如何在python中写hive脚本
Nov 08 Python
TensorFlow 多元函数的极值实例
Feb 10 Python
基于注解实现 SpringBoot 接口防刷的方法
Mar 02 Python
5行Python代码实现一键批量扣图
Jun 29 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实现多级树型菜单
2006/10/09 PHP
php使用GeoIP库实例
2014/06/27 PHP
php微信扫码支付 php公众号支付
2019/03/24 PHP
javascript中的几个运算符
2007/06/29 Javascript
单击复制文字兼容各浏览器的完美解决方案
2013/07/04 Javascript
GridView中获取被点击行中的DropDownList和TextBox中的值
2013/07/18 Javascript
JS实现超过长度限制后自动跳转下一款文本框的方法
2015/02/23 Javascript
JavaScript基本语法学习教程
2016/01/14 Javascript
轻量级jQuery插件slideBox实现带底栏轮播(焦点图)代码
2016/03/28 Javascript
JS中使用mailto实现将用户在网页中输入的内容传递到本地邮件客户端
2016/10/08 Javascript
Js动态设置rem来实现移动端字体的自适应代码
2016/10/14 Javascript
JavaScript组成、引入、输出、运算符基础知识讲解
2016/12/08 Javascript
vue2之简易的pc端短信验证码的问题及处理方法
2019/06/03 Javascript
angula中使用iframe点击后不执行变更检测的问题
2020/05/10 Javascript
Vue $emit()不能触发父组件方法的原因及解决
2020/07/28 Javascript
js中实现继承的五种方法
2021/01/25 Javascript
[00:15]天涯墨客终极技能展示
2018/08/25 DOTA
[46:12]完美世界DOTA2联赛循环赛 DM vs Matador BO2第一场 11.04
2020/11/04 DOTA
python实现随机密码字典生成器示例
2014/04/09 Python
Mac中Python 3环境下安装scrapy的方法教程
2017/10/26 Python
django认证系统 Authentication使用详解
2019/07/22 Python
Python面向对象之Web静态服务器
2019/09/03 Python
Python通过递归获取目录下指定文件代码实例
2019/11/07 Python
Python中内建模块collections如何使用
2020/05/27 Python
python speech模块的使用方法
2020/09/09 Python
video结合canvas实现视频在线截图功能
2018/06/25 HTML / CSS
HTML5中的Scoped属性使用实例
2014/04/23 HTML / CSS
基于HTML5的WebGL经典3D虚拟机房漫游动画
2017/11/15 HTML / CSS
数据库专业英语
2012/11/30 面试题
音乐教学随笔感言
2014/02/19 职场文书
新闻学专业求职信
2014/07/28 职场文书
2015国庆66周年宣传语
2015/07/14 职场文书
党校团干班培训心得体会
2016/01/06 职场文书
关于感恩的素材句子(38句)
2019/11/11 职场文书
八年级作文之友情
2019/11/25 职场文书
Pandas自定义选项option设置
2021/07/25 Python