学习目的:

  urllib提供了url解析函数,所以需要学习
正式步骤

Step1:什么是urllib

  urllib库是Python自带模块,是Python内置的HTTP请求库

  包含4个模块:
  

>>> import urllib
>>> # urllib.request  请求模块
>>> # urllib.error  异常处理模块
>>> # urllib.parse  url解析模块
>>> # urllib.robotparser  robot.txt解析模块

Step2:用法讲解

  1. urlopen

    # -*-  coding:utf-8 -*
    
    import urllib.request
    
    '''
    urlopen语法格式如下
    urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,*, cafile=None, capath=None, cadefault=False, context=None)
    '''
    #示例1
    response = urllib.request.urlopen('http://www.baidu.com')
    print(response.read().decode('utf-8')) #read()方法是获取了response内容,然后指定编码打印出来,如果不加decode,那么打印则显示在一行 print('\n')
    print('urllib.parse实例')
    print('\n')
    import urllib.request
    import urllib.parse data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')
    response = urllib.request.urlopen('http://httpbin.org/post',data=data)
    print(response.read()) print('\n')
    print('urllib中的timeout用法和urllib.error异常处理模块')
    print('\n') import urllib.request
    import socket
    import urllib.error
    try:
    response = urllib.request.urlopen('http://httpbin.org/get',timeout=0.1)
    except urllib.error.URLError as e:
    if isinstance(e.reason,socket.error):
    print('TIMEOUT')
  2. 响应
    # -*-  coding:utf-8 -*-
    
    print("响应类型实例")
    
    import urllib.request
    
    response = urllib.request.urlopen('http://www.baidu.com')
    print(type(response))
  3. 状态码和响应头
    # -*-  coding:utf-8 -*-
    
    print('状态码和响应头的实例')
    
    import urllib.request
    
    response = urllib.request.urlopen('http://www.baidu.com')
    print(response.status)
    print(response.getheaders())
    print(response.getheader('Content-Type'))
    print(response.getheader('Date'))
    print(response.getheader('Server'))

    运行结果

    状态码和响应头的实例
    200
    [('Date', 'Tue, 03 Apr 2018 14:29:52 GMT'), ('Content-Type', 'text/html; charset=utf-8'), ('Transfer-Encoding', 'chunked'), ('Connection', 'Close'), ('Vary', 'Accept-Encoding'), ('Set-Cookie', 'BAIDUID=6150350FD6AF7F0B4629DA49AEF7DEAE:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com'), ('Set-Cookie', 'BIDUPSID=6150350FD6AF7F0B4629DA49AEF7DEAE; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com'), ('Set-Cookie', 'PSTM=1522765792; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com'), ('Set-Cookie', 'BDSVRTM=0; path=/'), ('Set-Cookie', 'BD_HOME=0; path=/'), ('Set-Cookie', 'H_PS_PSSID=1430_25809_13290_21093_20927; path=/; domain=.baidu.com'), ('P3P', 'CP=" OTI DSP COR IVA OUR IND COM "'), ('Cache-Control', 'private'), ('Cxy_all', 'baidu+66a85a47dcb1b7de8cd2d7ba25b3a1dc'), ('Expires', 'Tue, 03 Apr 2018 14:29:42 GMT'), ('X-Powered-By', 'HPHP'), ('Server', 'BWS/1.1'), ('X-UA-Compatible', 'IE=Edge,chrome=1'), ('BDPAGETYPE', ''), ('BDQID', '0xa1de1b2000003abd'), ('BDUSERID', '')]
    text/html; charset=utf-8
    Tue, 03 Apr 2018 14:29:52 GMT
    BWS/1.1
  4. handler 代理
    # -*-  coding:utf-8 -*-
    import urllib.request proxy_hander = urllib.request.ProxyHandler(
    {'http':'http://127.0.0.1:9743','https':'https://127.0.0.1:9743'}
    )#代理以实际代理为准
    opener = urllib.request.build_opener(proxy_hander)
    response = opener.open('http://www.baidu.com')
    print(response.read())
  5. cookie (记录用户身份的文本文件)
    # -*-  coding:utf-8 -*-
    import urllib.request,http.cookiejar
    #将cookie保存
    filename = 'cookie.txt'
    cookie = http.cookiejar.LWPCookieJar(filename)
    hander = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(hander)
    responer = opener.open('http://www.baidu.com')
    cookie.save(ignore_discard=True,ignore_expires=True)

    打印cookie

    # -*-  coding:utf-8 -*-
    
    import urllib.request,http.cookiejar
    
    #声明cookie为cookiejar对象
    cookie = http.cookiejar.CookieJar()
    #hander是处理浏览器中的cookie作用
    hander = urllib.request.HTTPCookieProcessor(cookie)
    #利用build_opener将cookie传给opener
    opener = urllib.request.build_opener(hander)
    responser = opener.open('http://www.baidu.com')
    for i in cookie:
    print(i.name + '=' + i.value)

    将本地的cookie值赋到浏览器

    # -*-  coding:utf-8 -*-
    
    import urllib.request,http.cookiejar
    
    cookie = http.cookiejar.LWPCookieJar()
    cookie.load('cookie.txt',ignore_discard=True,ignore_expires=True)
    hander = urllib.request.HTTPCookieProcessor(cookie)
    opener = urllib.request.build_opener(hander)
    response = opener.open('http://www.baidu.com')
    print(response.read().decode('utf-8'))

学习总结:

  其余的内置方法未操作,直接学习下一节requests库

Python爬虫学习==>第七章:urllib库的基本使用方法的更多相关文章

  1. python爬虫---从零开始(二)Urllib库

    接上文再继续我们的爬虫,这次我们来述说Urllib库 1,什么是Urllib库 Urllib库是python内置的HTTP请求库 urllib.request 请求模块 urllib.error 异常 ...

  2. Python爬虫学习==>第八章:Requests库详解

    学习目的: request库比urllib库使用更加简洁,且更方便. 正式步骤 Step1:什么是requests requests是用Python语言编写,基于urllib,采用Apache2 Li ...

  3. Python爬虫(2):urllib库

    爬虫常用库urllib 注:运行环境为PyCharm urllib是Python3内置的HTTP请求库 urllib.request:请求模块 urllib.error:异常处理模块 urllib.p ...

  4. 【Python爬虫】HTTP基础和urllib库、requests库的使用

    引言: 一个网络爬虫的编写主要可以分为三个部分: 1.获取网页 2.提取信息 3.分析信息 本文主要介绍第一部分,如何用Python内置的库urllib和第三方库requests库来完成网页的获取.阅 ...

  5. Python爬虫学习==>第五章:爬虫常用库的安装

    学习目的: 爬虫有请求库(request.selenium).解析库.存储库(MongoDB.Redis).工具库,此节学习安装常用库的安装 正式步骤 Step1:urllib和re库 这两个库在安装 ...

  6. Python爬虫学习==>第十一章:分析Ajax请求-抓取今日头条信息

    学习目的: 解决AJAX请求的爬虫,网页解析库的学习,MongoDB的简单应用 正式步骤 Step1:流程分析 抓取单页内容:利用requests请求目标站点,得到单个页面的html代码,返回结果: ...

  7. Python爬虫学习==>第六章:爬虫的基本原理

    学习目的: 掌握爬虫相关的基本概念 正式步骤 Step1:什么是爬虫 请求网站并提取数据的自动化程序 Step2:爬虫的基本流程 Step3:Request和Response 1.request 2. ...

  8. python爬虫学习(三):使用re库爬取"淘宝商品",并把结果写进txt文件

    第二个例子是使用requests库+re库爬取淘宝搜索商品页面的商品信息 (1)分析网页源码 打开淘宝,输入关键字“python”,然后搜索,显示如下搜索结果 从url连接中可以得到搜索商品的关键字是 ...

  9. Python爬虫学习==>第三章:Redis环境配置

    学习目的: 学习非关系型数据库环境安装,为后续的分布式爬虫做基建 正式步骤 Step1:安装Redis 打开http://www.runoob.com/,搜索redis安装 打开搜索的内容,得到red ...

随机推荐

  1. 解决tomcat控制台乱码+清除过期缓存条目后可用空间仍不足 - 请考虑增加缓存的最大空间问题

    一.乱码 1.打开Tomcat的目录,找到conf文件夹,一般修改server.xml中的编码集,改为utf-8即可 2.若server.xml中编码设置的就是utf-8,可以修改logging.pr ...

  2. HNOI2004 树的计数 和 HNOI2008 明明的烦恼

    树的计数 输入文件第一行是一个正整数n,表示树有n个结点.第二行有n个数,第i个数表示di,即树的第i个结点的度数.其中1<=n<=150,输入数据保证满足条件的树不超过10^17个. 明 ...

  3. 帝都之行9day:正式上班第一天

    今天是我正式上班的第一天. 面了两天,三家公司,然后周五就去办入职了,我是不是太随便了点,捂脸. 不管怎么说,又要开始上班啦,CRUD的日子又要开始了…… 加油吧!

  4. es聚合学习笔记

    聚合可以做什么? count avg filter and count 每月新增 top 是否存在不正常或不符合规则的数据 关键概念 Buckets group by 将数据按某种标准划分成不同集合 ...

  5. Java-JsonUtil工具类

    import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; i ...

  6. vue cli3 + cube-ui 配置rem踩坑记录

    在install cube-ui时,选择了后编译,选中使用rem的时候会发现,怎么刷新页面的html字体被设置成了37.5px 感觉太大了,于是去寻找修改的办法,第一反应是webpack的配置,于是去 ...

  7. MySQL-5.6.13解压版(zip版)安装配置教程

    来源:http://www.splaybow.com/post/mysql-5-6-13-zip-install.html [下载MySQL 5.6.13] 从MySQL官方网站mysql.com找到 ...

  8. Confluence 6.15 博客页面(Blog Posts)宏

    博客页面宏允许你 Confluence 页面中显示博客页面.通过单击博客的标题将会把你链接到博客页面中. 使用博客页面宏 为了将博客页面宏添加到页面中:  从编辑工具栏中,选择 插入(Insert)  ...

  9. [题解] [CF451E] Devu and Flowers

    题面 题解 就是一个求\(\sum_{i= 1}^{n}x _ i = m\)的不重复多重集的个数, 我们可以由容斥原理得到: \[ ans = C_{n + m - 1}^{n - 1} - \su ...

  10. Spring boot 读取resource目录下的文件

    背景:最近做项目重构将以前的ssh + angular js架构,重构为spring boot + vue.项目是一个数据管理平台,后台涉及到多表关联查询,数据导入导出等. 问题:读取resource ...