【转】Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)
urllib是python的一个获取url(Uniform Resource Locators,统一资源定址器)了,我们可以利用它来抓取远程的数据进行保存哦,下面整理了一些关于urllib使用中的一些关于header,代理,超时,认证,异常处理处理方法,下面一起来看看。
python3 抓取网页资源的 N 种方法
1、最简单
1 import urllib.request
2
3 response = urllib.request.urlopen('http://python.org/')
4
5 html = response.read()
2、使用 Request

1 import urllib.request
2
3 req = urllib.request.Request('http://python.org/')
4
5 response = urllib.request.urlopen(req)
6
7 the_page = response.read()

3、发送数据

1 #! /usr/bin/env python3
2
3 import urllib.parse
4
5 import urllib.request
6
7 url = 'http://localhost/login.php'
8
9 user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
10
11 values = { 'act' : 'login', 'login[email]' : 'abc@abc.com', 'login[password]' : '123456' }
12
13 data = urllib.parse.urlencode(values)
14
15 req = urllib.request.Request(url, data)
16
17 req.add_header('Referer', 'http://www.python.org/')
18
19 response = urllib.request.urlopen(req)
20
21 the_page = response.read()
22
23 print(the_page.decode("utf8"))

4、发送数据和header

1 #! /usr/bin/env python3
2
3 import urllib.parse
4
5 import urllib.request
6
7 url = 'http://localhost/login.php'
8
9 user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
10
11 values = { 'act' : 'login', 'login[email]' : 'abc@abc.com', 'login[password]' : '123456' }
12
13 headers = { 'User-Agent' : user_agent }
14
15 data = urllib.parse.urlencode(values)
16
17 req = urllib.request.Request(url, data, headers)
18
19 response = urllib.request.urlopen(req)
20
21 the_page = response.read()
22
23 print(the_page.decode("utf8"))

5、http 错误

1 #! /usr/bin/env python3
2
3 import urllib.request
4
5 req = urllib.request.Request('http://python.org/')
6
7 try:
8
9 urllib.request.urlopen(req)
10
11 except urllib.error.HTTPError as e:
12
13 print(e.code)
14
15 print(e.read().decode("utf8"))

6、异常处理1

1 #! /usr/bin/env python3
2
3 from urllib.request import Request, urlopen
4
5 from urllib.error import URLError, HTTPError
6
7 req = Request('http://www.python.org/')
8
9 try:
10
11 response = urlopen(req)
12
13 except HTTPError as e:
14
15 print('The (www.python.org)server couldn't fulfill the request.')
16
17 print('Error code: ', e.code)
18
19 except URLError as e:
20
21 print('We failed to reach a server.')
22
23 print('Reason: ', e.reason)
24
25 else:
26
27 print("good!")
28
29 print(response.read().decode("utf8"))

7、异常处理2

1 #! /usr/bin/env python3
2
3 from urllib.request import Request, urlopen
4
5 from urllib.error import URLError
6
7 req = Request("http://www.python.org/")
8
9 try:
10
11 response = urlopen(req)
12
13 except URLError as e:
14
15 if hasattr(e, 'reason'):
16
17 print('We failed to reach a server.')
18
19 print('Reason: ', e.reason)
20
21 elif hasattr(e, 'code'):
22
23 print('The server couldn't fulfill the request.')
24
25 print('Error code: ', e.code)
26
27 else: print("good!")
28
29 print(response.read().decode("utf8"))

8、HTTP 认证

1 #! /usr/bin/env python3
2
3 import urllib.request
4
5 # create a password manager
6
7 password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
8
9 # Add the username and password.
10
11 # If we knew the realm, we could use it instead of None.
12
13 top_level_url = "https://www.python.org/"
14
15 password_mgr.add_password(None, top_level_url, 'rekfan', 'xxxxxx')
16
17 handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
18
19 # create "opener" (OpenerDirector instance)
20
21 opener = urllib.request.build_opener(handler)
22
23 # use the opener to fetch a URL
24
25 a_url = "https://www.python.org/"
26
27 x = opener.open(a_url)
28
29 print(x.read())
30
31 # Install the opener.
32
33 # Now all calls to urllib.request.urlopen use our opener.
34
35 urllib.request.install_opener(opener)
36
37 a = urllib.request.urlopen(a_url).read().decode('utf8')
38
39 print(a)

9、使用代理

1 #! /usr/bin/env python3
2
3 import urllib.request
4
5 proxy_support = urllib.request.ProxyHandler({'sock5': 'localhost:1080'})
6
7 opener = urllib.request.build_opener(proxy_support)
8
9 urllib.request.install_opener(opener)
10
11 a = urllib.request.urlopen("http://www.python.org/").read().decode("utf8")
12
13 print(a)

10、超时

1 #! /usr/bin/env python3
2
3 import socket
4
5 import urllib.request
6
7 # timeout in seconds
8
9 timeout = 2
10
11 socket.setdefaulttimeout(timeout)
12
13 # this call to urllib.request.urlopen now uses the default timeout
14
15 # we have set in the socket module
16
17 req = urllib.request.Request('http://www.python.org/')
18
19 a = urllib.request.urlopen(req).read()
20
21 print(a)

来源:http://www.cnblogs.com/ifso/p/4707135.html
【转】Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)的更多相关文章
- Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)
urllib是python的一个获取url(Uniform Resource Locators,统一资源定址器)了,我们可以利用它来抓取远程的数据进行保存哦,下面整理了一些关于urllib使用中的一些 ...
- Python3中urllib详细使用方法(header,代理,超时,认证,异常处理) 转
urllib是python的一个获取url(Uniform Resource Locators,统一资源定址器)了,我们可以利用它来抓取远程的数据进行保存哦,下面整理了一些关于urllib使用中的一些 ...
- Python3中使用urllib的方法详解(header,代理,超时,认证,异常处理)_python
我们可以利用urllib来抓取远程的数据进行保存哦,以下是python3 抓取网页资源的多种方法,有需要的可以参考借鉴. 1.最简单 import urllib.request response = ...
- Python3中使用urllib的方法详解(header,代理,超时,认证,异常处理)
出自 http://www.jb51.net/article/93125.htm
- Python2和Python3中urllib库中urlencode的使用注意事项
前言 在Python中,我们通常使用urllib中的urlencode方法将字典编码,用于提交数据给url等操作,但是在Python2和Python3中urllib模块中所提供的urlencode的包 ...
- python3中使用builtwith的方法(很详细)
1. 首先通过pip install builtwith安装builtwith C:\Users\Administrator>pip install builtwith Collecting b ...
- python3中urllib库的request模块详解
刚刚接触爬虫,基础的东西得时时回顾才行,这么全面的帖子无论如何也得厚着脸皮转过来啊! 原帖地址:https://www.2cto.com/kf/201801/714859.html 什么是 Urlli ...
- Python3中Urllib库基本使用
什么是Urllib? Python内置的HTTP请求库 urllib.request 请求模块 urllib.error 异常处理模块 urllib.par ...
- python3中urllib的基本使用
urllib 在python3中,urllib和urllib2进行了合并,现在只有一个urllib模块,urllib和urllib2的中的内容整合进了urllib.request,urlparse整合 ...
随机推荐
- spring cloud 专题二(spring cloud 入门搭建 之 微服务搭建和注册)
一.前言 本文为spring cloud 微服务框架专题的第二篇,主要讲解如何快速搭建微服务以及如何注册. 本文理论不多,主要是傻瓜式的环境搭建,适合新手快速入门. 为了更好的懂得原理,大家可以下载& ...
- servlet的执行过程
第一次访问servlet的过程: 服务器启动:在服务器启动的时候,加载项目,就扫描web.xml文件,获得应用有哪些servlet,url-pattern, 客户端通过URl访问服务器[向服务器发送一 ...
- React 组件间通讯
React 组件间通讯 说 React 组件间通讯之前,我们先来讨论一下 React 组件究竟有多少种层级间的关系.假设我们开发的项目是一个纯 React 的项目,那我们项目应该有如下类似的关系: 父 ...
- APK Multi-Tool强大的APK反编译工具终极教程
一.APK Multi-Tool介绍 APK Multi-Tool 是APK Manager的升级版,是一个强大的APK反编译工具,集多种功能于一身,是居家必备.做ROM必选的工具! 这是 ...
- 理解JAVA内存模型
实际上java内存模型是如上图所示一样 每个线程有自己的栈内存,存放共享对象的副本,本地变量 每个线程自己的本地变量是不可见的,但是共享对象对每个线程都是可见的. 如果想实现线程通信的话, 线程对共享 ...
- 数据库数据带&符号 导入有问题的处理办法
在sql文件头部加个: set feedback off set define off 我们在plsql里面将一条语句导出时会出现以下结果(测试表t_test): prompt Importing ...
- Struts2 之 Action 类访问 WEB 资源
接着上次博客的内容我继续分享我所学到的知识,和自己在学习过程中所遇到问题以及解决方案.当然,如果读者发现任何问题均可以在下方评论告知我,先谢! 在 Action 中访问 WEB 资源 web 资源 所 ...
- Git详细教程(2)---多人协作开发
Git可以完成两件事情: 1. 版本控制 2.多人协作开发 如今的项目,规模越来越大,功能越来越多,需要有一个团队进行开发. 如果有多个开发人员共同开发一个项目,如何进行协作的呢. Git提供了一个非 ...
- Mybatis学习笔记一
Mybatis介绍 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为M ...
- 【LATEX】个人版latex论文模板
以下是我的个人论文模板,运行环境为Xelatex(在线ide:Sharelatex.com) 鉴于本人常有插入程序的需求,故引用了lstlisting \RequirePackage{ifxetex} ...