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在linux中输出带颜色的文字的方法
Jun 19 Python
Python求导数的方法
May 09 Python
python实现提取百度搜索结果的方法
May 19 Python
对pandas中时间窗函数rolling的使用详解
Nov 28 Python
Python requests模块实例用法
Feb 11 Python
python判断所输入的任意一个正整数是否为素数的两种方法
Jun 27 Python
python GUI库图形界面开发之PyQt5窗口类QMainWindow详细使用方法
Feb 26 Python
Python叠加矩形框图层2种方法及效果
Jun 18 Python
python 使用xlsxwriter循环向excel中插入数据和图片的操作
Jan 01 Python
scrapy实践之翻页爬取的实现
Jan 05 Python
pycharm 的Structure界面设置操作
Feb 05 Python
win10+anaconda安装yolov5的方法及问题解决方案
Apr 29 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创建动态图像
2006/10/09 PHP
PHP 超链接 抓取实现代码
2009/06/29 PHP
php接口实现拖拽排序功能
2018/04/23 PHP
php数值计算num类简单操作示例
2020/05/15 PHP
JS按位非(~)运算符与~~运算符的理解分析
2011/07/31 Javascript
基于mootools插件实现遮罩层新手引导
2012/05/24 Javascript
Js中setTimeout()和setInterval() 何时被调用执行的用法
2013/04/12 Javascript
javascript中不等于的代码是什么怎么写
2013/12/29 Javascript
window.onload与$(document).ready()的区别分析
2015/05/30 Javascript
js为什么不能正确处理小数运算?
2015/12/29 Javascript
JavaScript数组操作函数汇总
2016/08/05 Javascript
封装的dialog插件 基于bootstrap模态对话框的简单扩展
2016/08/10 Javascript
详解Angular中$cacheFactory缓存的使用
2016/08/19 Javascript
谈谈target=_new和_blank的不同之处
2016/10/25 Javascript
jQuery中map函数的两种方式
2017/04/07 jQuery
Angular 4依赖注入学习教程之Injectable装饰器(六)
2017/06/04 Javascript
解决Vue2.0中使用less给元素添加背景图片出现的问题
2018/09/03 Javascript
javascript实现考勤日历功能
2018/11/29 Javascript
vue2.0 如何在hash模式下实现微信分享
2019/01/22 Javascript
layui表单验证select下拉框实现验证的方法
2019/09/05 Javascript
在vue中axios设置timeout超时的操作
2020/09/04 Javascript
javascript实现点击小图显示大图
2020/11/29 Javascript
python监控进程脚本
2018/04/12 Python
Python 实现文件读写、坐标寻址、查找替换功能
2019/09/11 Python
python对数组进行排序,并输出排序后对应的索引值方式
2020/02/28 Python
css3中单位px,em,rem,vh,vw,vmin,vmax的区别及浏览器支持情况
2016/12/06 HTML / CSS
送给他或她的礼物:FUN.com
2018/08/17 全球购物
制冷与电控专业应届生求职信
2013/11/11 职场文书
优秀毕业生自荐信范文
2014/01/01 职场文书
医校毕业生自我鉴定
2014/01/25 职场文书
校长先进事迹材料
2014/02/01 职场文书
酒店营销策划方案
2014/02/07 职场文书
幼儿园大班评语大全
2014/04/17 职场文书
社区巾帼文明岗事迹材料
2014/06/03 职场文书
网络工程专业大学生求职信
2014/10/01 职场文书
有关浪费资源的建议书
2015/09/14 职场文书