这周打算把学过的内容重新总结一下,便于以后翻阅查找资料。

urllib库是python的内置库,不需要单独下载。其主要分为四个模块:

1.urllib.request——请求模块

2.urllib.error——异常处理模块

3.urllib.parse——url解析模块

4.urllib.robotparser——用来识别网站的robot.txt文件(看看哪些内容是可以爬的,不常用)

1.urlopen

import urllib.request

response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))
超时读取
import socket
import urllib.request
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.timeout):
print('TIME OUT')
响应内容分析
import urllib.request response = urllib.request.urlopen('https://www.python.org')
print(type(response))
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))
<class 'http.client.HTTPResponse'>
200
[('Server', 'nginx'), ('Content-Type', 'text/html; charset=utf-8'), ('X-Frame-Options', 'SAMEORIGIN'), ('x-xss-protection', '1; mode=block'), ('X-Clacks-Overhead', 'GNU Terry Pratchett'), ('Via', '1.1 varnish'), ('Content-Length', '50069'), ('Accept-Ranges', 'bytes'), ('Date', 'Mon, 26 Nov 2018 02:44:49 GMT'), ('Via', '1.1 varnish'), ('Age', '3121'), ('Connection', 'close'), ('X-Served-By', 'cache-iad2150-IAD, cache-sjc3143-SJC'), ('X-Cache', 'MISS, HIT'), ('X-Cache-Hits', '0, 254'), ('X-Timer', 'S1543200290.644687,VS0,VE0'), ('Vary', 'Cookie'), ('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]
nginx

2. request

用来传递更多的请求参数,url,headers,data, method
from urllib import request, parse url = 'http://httpbin.org/post'
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
'Host': 'httpbin.org'
}
dict = {
'name': 'Germey'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, headers=headers, method='POST')
response = request.urlopen(req)
print(response.read().decode('utf-8'))
{
"args": {},
"data": "",
"files": {},
"form": {
"name": "Germey"
},
"headers": {
"Accept-Encoding": "identity",
"Connection": "close",
"Content-Length": "11",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"
},
"json": null,
"origin": "117.136.66.101",
"url": "http://httpbin.org/post"
}
另一种方法添加headers

from urllib import request, parse

url = 'http://httpbin.org/post'
dict = {
'name': 'asd'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, method='POST')
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)') #如果有好多headers,可以循环添加
response = request.urlopen(req)
print(response.read().decode('utf-8'))

3. Handler

代理
import urllib.request proxy_handler = urllib.request.ProxyHandler({
'http': 'http://127.0.0.1:9743',
'https': 'https://127.0.0.1:9743'
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('https://www.httpbin,org/get')
print(response.read())

4. Cookie

获取cookie
import http.cookiejar, urllib.request cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
for item in cookie:
print(item.name+"="+item.value)
存储Cookie
import http.cookiejar, urllib.request
filename = "cookie.txt"
cookie = http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True, ignore_expires=True)
获取Cookie
import http.cookiejar, urllib.request
cookie = http.cookiejar.MozillaCookieJar()
cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))

5. UrlError 和 HttpError

from urllib import request, error

try:
response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.HTTPError as e:
print(e.reason, e.code, e.headers, sep='\n')
except error.URLError as e:
print(e.reason)
else:
print('Request Successfully')

对于urllib.parse,因为用的不多,就先不写了。上传一个文档链接吧,万一哪天用了还可以看看。

https://files.cnblogs.com/files/zhangguoxv/urllib%E8%AE%B2%E8%A7%A3.zip

urllib库使用方法的更多相关文章

  1. urllib库使用方法 4 create headers

    import urllib.requestimport urllib.parse url = "https://www.baidu.com/"#普通请求方法response = u ...

  2. urllib库使用方法 3 get html

    import urllib.requestimport urllib.parse #https://www.baidu.com/s?ie=UTF-8&wd=中国#将上面的中国部分内容,可以动态 ...

  3. urllib库使用方法 2 parse

    import urllib.parse #url.parse用法包含三个方法:quote url, unquote rul, urlencode#quote url 编码函数,url规范只识别字母.数 ...

  4. urllib库使用方法1 request

    urllib是可以模仿浏览器发送请求的库,Python自带 Python3中urllib分为:urllib.request和urllib.parse import urllib.request url ...

  5. Python爬虫学习==>第七章:urllib库的基本使用方法

    学习目的: urllib提供了url解析函数,所以需要学习正式步骤 Step1:什么是urllib urllib库是Python自带模块,是Python内置的HTTP请求库 包含4个模块: >& ...

  6. python--爬虫入门(七)urllib库初体验以及中文编码问题的探讨

    python系列均基于python3.4环境 ---------@_@? --------------------------------------------------------------- ...

  7. urllib库初体验以及中文编码问题的探讨

    提出问题:如何简单抓取一个网页的源码 解决方法:利用urllib库,抓取一个网页的源代码 ------------------------------------------------------- ...

  8. Python爬虫入门 Urllib库的基本使用

    1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它是一段HTML代码,加 JS.CSS ...

  9. Python爬虫入门:Urllib库的基本使用

    1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它 是一段HTML代码,加 JS.CS ...

随机推荐

  1. Java实现第七届蓝桥杯国赛 赢球票

    标题:赢球票 某机构举办球票大奖赛.获奖选手有机会赢得若干张球票. 主持人拿出 N 张卡片(上面写着 1~N 的数字),打乱顺序,排成一个圆圈. 你可以从任意一张卡片开始顺时针数数: 1,2,3- 如 ...

  2. Java实现 LeetCode 551 学生出勤记录 I(暴力大法好)

    551. 学生出勤记录 I 给定一个字符串来代表一个学生的出勤记录,这个记录仅包含以下三个字符: 'A' : Absent,缺勤 'L' : Late,迟到 'P' : Present,到场 如果一个 ...

  3. Java实现 LeetCode 517 超级洗衣机

    517. 超级洗衣机 假设有 n 台超级洗衣机放在同一排上.开始的时候,每台洗衣机内可能有一定量的衣服,也可能是空的. 在每一步操作中,你可以选择任意 m (1 ≤ m ≤ n) 台洗衣机,与此同时将 ...

  4. Java实现 蓝桥杯VIP 算法提高 前10名

    算法提高 前10名 时间限制:1.0s 内存限制:256.0MB 问题描述 数据很多,但我们经常只取前几名,比如奥运只取前3名.现在我们有n个数据,请按从大到小的顺序,输出前10个名数据. 输入格式 ...

  5. 第03组 Alpha(2/4)

    队名:不等式方程组 组长博客 作业博客 团队项目进度 组员一:张逸杰(组长) 过去两天完成的任务: 文字/口头描述: 制定了初步的项目计划,并开始学习一些推荐.搜索类算法 GitHub签入纪录: 暂无 ...

  6. 安装fail2ban,防止ssh爆破及cc攻击

    背景:之前写过shell脚本防止服务器ssh爆破,但是对于服务器的cpu占用较多,看来下资料安装fail2ban 可以有效控制ssh爆破 1:fail2ban 安装(环境:centos6  宝塔) y ...

  7. Python3和Python2中int和long的区别?

    Python3:Python3中int类型的范围是动态长度的,正整数或者负整数,用sys.getsizeof()可以看int占了几位. Python2:Python2中long类型的范围是无限大小.

  8. java类的加载顺序和实例化顺序(Demo程序)

    一.main函数中实例化对象 父类 package com.learn; public class Father { //静态变量 public static int num_1 = 1; //静态代 ...

  9. 常见ie9兼容问题

    公司项目要求需要兼容ie9,开发过程中遇到了许多问题,在这里记录一下,希望可以帮到其他需要的小伙伴. 浏览器兼容性问题无外乎三点,css样式兼容.JavaScript兼容及h5部分标签的兼容.主要介绍 ...

  10. centos6 升级python2.6 到 python2.7

    由于开发库依赖于python27,而自己安装的centos6.8自带的python是2.6.6. 因为centos的yum依赖于python26因此不打算覆盖26. 步骤如下: 1.官网下载源码压缩包 ...