侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python3学习urllib的使用方法示例

Python  /  管理员 发布于 7年前   176

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 requestresponse = 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:// /" 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:// /" 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('// /') a = urllib.request.urlopen(req).read() print(a) 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Python快速排序算法实例分析
    下一条:
    Python实现的选择排序算法示例
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客