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]‘ : ‘[email protected]‘,  ‘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]‘ : ‘[email protected]‘,  ‘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)
时间: 2024-08-05 07:05:48

Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)的相关文章

Python3中urllib详细使用方法(header,代理,超时,认证,异常处理) 转载

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

【转】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

python3中使用builtwith的方法(很详细)

1. 首先通过pip install builtwith安装builtwith C:\Users\Administrator>pip install builtwith Collecting builtwith Downloading builtwith-1.3.2.tar.gz Installing collected packages: builtwith Running setup.py install for builtwith ... done Successfully install

Python3中urllib使用与源代码

Py2.x: Urllib库 Urllin2库 Py3.x: Urllib库 变化: 在Pytho2.x中使用import urllib2---对应的,在Python3.x中会使用import urllib.request,urllib.error. 在Pytho2.x中使用import urllib---对应的,在Python3.x中会使用import urllib.request,urllib.error,urllib.parse. 在Pytho2.x中使用import urlparse--

Python3中BeautifulSoup的使用方法

BeautifulSoup的使用 我们学习了正则表达式的相关用法,但是一旦正则写的有问题,可能得到的就不是我们想要的结果了,而且对于一个网页来说,都有一定的特殊的结构和层级关系,而且很多标签都有id或class来对作区分,所以我们借助于它们的结构和属性来提取不也是可以的吗? 所以,这一节我们就介绍一个强大的解析工具,叫做BeautiSoup,它就是借助网页的结构和属性等特性来解析网页的工具,有了它我们不用再去写一些复杂的正则,只需要简单的几条语句就可以完成网页中某个元素的提取. 废话不多说,接下

python3中urllib.request.urlopen.read读取的网页格式问题

#!/usr/bin/env python3 #-*- coding: utf-8 -*- #<a title="" target="_blank" href="http://blog.sina.com.cn/s/blog_4701280b0102eo83.html"><论电影的七个元素>——关于我对电…</a> import urllib.request str0 =r' <a title="

【Python】python3中urllib爬虫开发

以下是三种方法 ①First Method 最简单的方法 ②添加data,http header 使用Request对象 ③CookieJar import urllib.request from http import cookiejar url ='http://www.baidu.com' print("First Method") response1 = urllib.request.urlopen(url) #返回状态码 print(response1.getcode())

JS中showModalDialog 详细使用方法

基本介绍: showModalDialog() (IE 4+ 支持) showModelessDialog() (IE 5+ 支持) window.showModalDialog() 方法用来创建一个显示HTML内容的模态对话框. window.showModelessDialog() 方法用来创建一个显示HTML内容的非模态对话框. 使用方法: vReturnValue = window.showModalDialog(sURL [, vArguments] [,sFeatures]) vRe

python爬虫开发之urllib模块详细使用方法与实例全解

爬虫所需要的功能,基本上在urllib中都能找到,学习这个标准库,可以更加深入的理解后面更加便利的requests库. 首先 在Pytho2.x中使用import urllib2——-对应的,在Python3.x中会使用import urllib.request,urllib.error 在Pytho2.x中使用import urllib——-对应的,在Python3.x中会使用import urllib.request,urllib.error,urllib.parse 在Pytho2.x中使