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中的正则表达式的用法
Apr 09 Python
python实现指定字符串补全空格的方法
Apr 30 Python
Python中集合的内建函数和内建方法学习教程
Aug 19 Python
详解Python中类的定义与使用
Apr 11 Python
Python模块结构与布局操作方法实例分析
Jul 24 Python
基于python 处理中文路径的终极解决方法
Apr 12 Python
Django接收自定义http header过程详解
Aug 23 Python
python爬虫爬取监控教务系统的思路详解
Jan 08 Python
Django后台管理系统的图文使用教学
Jan 20 Python
python 抓取知乎指定回答下视频的方法
Jul 09 Python
python3 re返回形式总结
Nov 20 Python
python之json文件转xml文件案例讲解
Aug 07 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获取短链接跳转后的真实地址和响应头信息的方法
2014/07/25 PHP
php实现模拟登陆方正教务系统抓取课表
2015/05/19 PHP
PHPExcel实现表格导出功能示例【带有多个工作sheet】
2018/06/13 PHP
php使用filter_var函数判断邮箱,url,ip格式示例
2019/07/06 PHP
可缩放Reloaded-一个针对可缩放元素的复用组件
2007/03/10 Javascript
JavaScript删除指定子元素代码实例
2015/01/13 Javascript
Jquery动态添加输入框的方法
2015/05/29 Javascript
jquery实现表格中点击相应行变色功能效果【实例代码】
2016/05/09 Javascript
JavaScript EventEmitter 背后的秘密 完整版
2018/03/29 Javascript
微信小程序表单验证form提交错误提示效果
2020/06/19 Javascript
JS数组方法reduce的用法实例分析
2020/03/03 Javascript
使用Vue 自定义文件选择器组件的实例代码
2020/03/04 Javascript
JS实现滑动拼图验证功能完整示例
2020/03/29 Javascript
vue实现整屏滚动切换
2020/06/29 Javascript
react中hook介绍以及使用教程
2020/12/11 Javascript
[59:15]EG vs LGD 2018国际邀请赛淘汰赛BO3 第一场 8.26
2018/08/29 DOTA
python 正则式 概述及常用字符
2009/05/07 Python
Python threading多线程编程实例
2014/09/18 Python
Djang中静态文件配置方法
2015/07/30 Python
利用Python将时间或时间间隔转为ISO 8601格式方法示例
2017/09/05 Python
python分布式环境下的限流器的示例
2017/10/26 Python
Python中pygal绘制雷达图代码分享
2017/12/07 Python
微信跳一跳小游戏python脚本
2018/01/05 Python
python实现比较文件内容异同
2018/06/22 Python
python使用yield压平嵌套字典的超简单方法
2019/11/02 Python
Python logging日志模块 配置文件方式
2020/07/12 Python
详解python的super()的作用和原理
2020/10/29 Python
英国最大的在线运动补充剂商店:Discount Supplements
2017/06/03 全球购物
SQL注入攻击的种类有哪些
2013/12/30 面试题
医学专业个人求职自荐信格式
2013/09/23 职场文书
农业大学毕业生的个人自我评价
2013/10/11 职场文书
幼儿园元旦亲子活动方案
2014/02/17 职场文书
2014年物业公司工作总结
2014/11/22 职场文书
实用求职信模板范文
2019/05/13 职场文书
MybatisPlus代码生成器的使用方法详解
2021/06/13 Java/Android
vue打包时去掉所有的console.log
2022/04/10 Vue.js