Python3学习urllib的使用方法示例


Posted in Python onNovember 29, 2017

urllib是python的一个获取url(Uniform Resource Locators,统一资源定址符)了,可以利用它来抓取远程的数据进行保存,本文整理了一些关于urllib使用中的一些关于header,代理,超时,认证,异常处理处理方法。

1.基本方法

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

  1. url:  需要打开的网址
  2. data:Post提交的数据
  3. timeout:设置网站的访问超时时间

直接用urllib.request模块的urlopen()获取页面,page的数据格式为bytes类型,需要decode()解码,转换成str类型。

from urllib import request
response = request.urlopen(r'http://python.org/') # <http.client.HTTPResponse object at 0x00000000048BC908> HTTPResponse类型
page = response.read()
page = page.decode('utf-8')

urlopen返回对象提供方法:

  1. read() , readline() ,readlines() , fileno() , close() :对HTTPResponse类型数据进行操作
  2. info():返回HTTPMessage对象,表示远程服务器返回的头信息
  3. getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到
  4. geturl():返回请求的url

1、简单读取网页信息

import urllib.request 
response = urllib.request.urlopen('http://python.org/') 
html = response.read()

2、使用request

urllib.request.Request(url, data=None, headers={}, method=None)

使用request()来包装请求,再通过urlopen()获取页面。

import urllib.request 
req = urllib.request.Request('http://python.org/') 
response = urllib.request.urlopen(req) 
the_page = response.read()

3、发送数据,以登录知乎为例

''''' 
Created on 2016年5月31日 
 
@author: gionee 
''' 
import gzip 
import re 
import urllib.request 
import urllib.parse 
import http.cookiejar 
 
def ungzip(data): 
  try: 
    print("尝试解压缩...") 
    data = gzip.decompress(data) 
    print("解压完毕") 
  except: 
    print("未经压缩,无需解压") 
   
  return data 
     
def getXSRF(data): 
  cer = re.compile('name=\"_xsrf\" value=\"(.*)\"',flags = 0) 
  strlist = cer.findall(data) 
  return strlist[0] 
 
def getOpener(head): 
  # cookies 处理 
  cj = http.cookiejar.CookieJar() 
  pro = urllib.request.HTTPCookieProcessor(cj) 
  opener = urllib.request.build_opener(pro) 
  header = [] 
  for key,value in head.items(): 
    elem = (key,value) 
    header.append(elem) 
  opener.addheaders = header 
  return opener 
# header信息可以通过firebug获得 
header = { 
  'Connection': 'Keep-Alive', 
  'Accept': 'text/html, application/xhtml+xml, */*', 
  'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3', 
  'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0', 
  'Accept-Encoding': 'gzip, deflate', 
  'Host': 'www.zhihu.com', 
  'DNT': '1' 
} 
 
url = 'http://www.zhihu.com/' 
opener = getOpener(header) 
op = opener.open(url) 
data = op.read() 
data = ungzip(data) 
_xsrf = getXSRF(data.decode()) 
 
url += "login/email" 
email = "登录账号" 
password = "登录密码" 
postDict = { 
  '_xsrf': _xsrf, 
  'email': email, 
  'password': password, 
  'rememberme': 'y'  
} 
postData = urllib.parse.urlencode(postDict).encode() 
op = opener.open(url,postData) 
data = op.read() 
data = ungzip(data) 
 
print(data.decode())

4、http错误

import urllib.request 
req = urllib.request.Request('http://www.lz881228.blog.163.com ') 
try: 
  urllib.request.urlopen(req) 
except urllib.error.HTTPError as e: 
print(e.code) 
print(e.read().decode("utf8"))

5、异常处理

from urllib.request import Request, urlopen 
from urllib.error import URLError, HTTPError 
 
req = Request("http://www.abc.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"))

6、http认证

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)

7、使用代理

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("http://www.baidu.com ").read().decode("utf8") 
print(a)

8、超时

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实现115网盘自动下载的方法
Sep 30 Python
python从入门到精通(DAY 2)
Dec 20 Python
在win和Linux系统中python命令行运行的不同
Jul 03 Python
Python中单、双下划线的区别总结
Dec 01 Python
利用TensorFlow训练简单的二分类神经网络模型的方法
Mar 05 Python
Python OpenCV处理图像之图像直方图和反向投影
Jul 10 Python
python基于Selenium的web自动化框架
Jul 14 Python
python实现与redis交互操作详解
Apr 21 Python
基于pycharm 项目和项目文件命名规则的介绍
Jan 15 Python
golang特有程序结构入门教程
Jun 02 Python
利用python调用摄像头的实例分析
Jun 07 Python
关于python类SortedList详解
Sep 04 Python
Python实现的选择排序算法示例
Nov 29 #Python
Python实现的桶排序算法示例
Nov 29 #Python
[原创]教女朋友学Python(一)运行环境搭建
Nov 29 #Python
对变量赋值的理解--Pyton中让两个值互换的实现方法
Nov 29 #Python
基于Python函数的作用域规则和闭包(详解)
Nov 29 #Python
JSONLINT:python的json数据验证库实例解析
Nov 28 #Python
详解如何使用Python编写vim插件
Nov 28 #Python
You might like
PHP将MySQL的查询结果转换为数组并用where拼接的示例
2016/05/13 PHP
PHP结合Vue实现滚动底部加载效果
2017/12/17 PHP
JavaScript 定义function的三种方式小结
2009/10/16 Javascript
对字符串进行HTML编码和解码的JavaScript函数
2010/02/01 Javascript
使用POST方式弹出窗口的两种方法示例介绍
2014/01/29 Javascript
javascript实现详细时间提醒信息效果的方法
2015/03/11 Javascript
javascript类型系统_正则表达式RegExp类型详解
2016/06/24 Javascript
bootstrap提示标签、提示框实现代码
2016/12/28 Javascript
详解Vue中一种简易路由传参办法
2017/09/15 Javascript
Vue2.0用户权限控制解决方案
2017/11/29 Javascript
vue、react等单页面项目部署到服务器的方法及vue和react的区别
2018/09/29 Javascript
vue代码分割的实现(codesplit)
2018/11/13 Javascript
在JavaScript中如何访问暂未存在的嵌套对象
2019/06/18 Javascript
如何阻止小程序遮罩层下方图层滚动
2019/09/05 Javascript
vue和iview实现Scroll 数据无限滚动功能
2019/10/31 Javascript
JavaScript oncopy事件用法实例解析
2020/05/13 Javascript
Nodejs 微信小程序消息推送的实现
2021/01/20 NodeJs
python在windows下实现备份程序实例
2014/07/04 Python
零基础写python爬虫之使用Scrapy框架编写爬虫
2014/11/07 Python
Python 列表list使用介绍
2014/11/30 Python
python实现可视化动态CPU性能监控
2018/06/21 Python
Python语言编写智力问答小游戏功能
2020/10/13 Python
Otticanet意大利:最顶尖的世界名牌眼镜, 能得到打折季的价格
2019/03/10 全球购物
美国第二大连锁药店:Rite Aid
2019/04/03 全球购物
Chemist Warehouse中文网:澳洲连锁大药房
2021/02/05 全球购物
经典优秀毕业生求职信范文分享
2013/12/18 职场文书
法人代表委托书
2014/04/04 职场文书
高一课前三分钟演讲稿
2014/09/13 职场文书
推广普通话共筑中国梦演讲稿
2014/09/21 职场文书
2015年教师党员自我评价材料
2015/03/04 职场文书
2015年教务主任工作总结
2015/07/22 职场文书
在酒桌上的敬酒词
2015/08/12 职场文书
初中体育课教学反思
2016/02/16 职场文书
教你如何用python开发一款数字推盘小游戏
2021/04/14 Python
pycharm 如何查看某一函数源码的快捷键
2021/05/12 Python
python游戏开发Pygame框架
2022/04/22 Python