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

 更新时间:2016年09月21日 11:37:59   作者:ifso  
这篇文章整理了一些关于urllib使用中的一些关于header,代理,超时,认证,异常处理处理方法,对大家学习python具有一定的参考借鉴价值,有需要的朋友们下面来一起看看吧。

我们可以利用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://www.jb51.net ')
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://www.jb51.net /")
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://www.jb51.net /")
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://www.jb51.net /"
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://www.jb51.net /"
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://www.jb51.net ").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://www.jb51.net /')
a = urllib.request.urlopen(req).read()
print(a)

总结

以上就是这篇文章的全部内容,希望本文的内容对大家学习或使用python能有所帮助,如果有疑问大家可以留言交流。

相关文章

  • 基于pandas数据清洗的实现示例

    基于pandas数据清洗的实现示例

    数据清洗是数据科学和数据分析中非常重要的一个步骤,本文主要介绍了基于pandas的数据清洗,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-07-07
  • Python爬虫,获取,解析,存储详解

    Python爬虫,获取,解析,存储详解

    这篇文章主要介绍了Python爬虫获取、解析,获数据操作,其中代码描述非常详细,需要的朋友可以参考下,希望能够给你带来帮助
    2021-10-10
  • flask框架路由常用定义方式总结

    flask框架路由常用定义方式总结

    这篇文章主要介绍了flask框架路由常用定义方式,结合实例形式总结分析了flask框架路由的常见定义方式与相关操作注意事项,需要的朋友可以参考下
    2019-07-07
  • Python统计中文词频的四种方法小结

    Python统计中文词频的四种方法小结

    统计中文词频是Python考试中常见的操作,本文我们总结了四种常见的中文词频统计方法,并列出代码,具有一定的参考价值,感兴趣的可以了解一下
    2023-08-08
  • Python如何通过ip2region解析IP获得地域信息

    Python如何通过ip2region解析IP获得地域信息

    这篇文章主要介绍了Python如何通过ip2region解析IP获得地域信息,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • tensorflow建立一个简单的神经网络的方法

    tensorflow建立一个简单的神经网络的方法

    本篇文章主要介绍了tensorflow建立一个简单的神经网络的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02
  • 约瑟夫问题的Python和C++求解方法

    约瑟夫问题的Python和C++求解方法

    这篇文章主要介绍了约瑟夫问题的Python和C++求解方法,通过其示例我们也可以看出如今写法最简洁的编程语言和最复杂的语言之间的对比:D 需要的朋友可以参考下
    2015-08-08
  • 解决usageerror: line magic function "%%time" not found问题

    解决usageerror: line magic function "

    这篇文章主要介绍了解决usageerror: line magic function "%%time" not found问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-01-01
  • py2exe 编译ico图标的代码

    py2exe 编译ico图标的代码

    py2exe 编译ico图标的代码,需要的朋友可以参考下
    2013-03-03
  • Python中的迭代器你了解吗

    Python中的迭代器你了解吗

    迭代器是一种特殊的对象,它实现了迭代协议,允许按照一定的顺序逐个访问元素,本文就来带大家深入了解一下Python中迭代器的使用,需要的可以参考下
    2023-05-05

最新评论