urllib库使用方法
这周打算把学过的内容重新总结一下,便于以后翻阅查找资料。
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库使用方法的更多相关文章
- urllib库使用方法 4 create headers
import urllib.requestimport urllib.parse url = "https://www.baidu.com/"#普通请求方法response = u ...
- urllib库使用方法 3 get html
import urllib.requestimport urllib.parse #https://www.baidu.com/s?ie=UTF-8&wd=中国#将上面的中国部分内容,可以动态 ...
- urllib库使用方法 2 parse
import urllib.parse #url.parse用法包含三个方法:quote url, unquote rul, urlencode#quote url 编码函数,url规范只识别字母.数 ...
- urllib库使用方法1 request
urllib是可以模仿浏览器发送请求的库,Python自带 Python3中urllib分为:urllib.request和urllib.parse import urllib.request url ...
- Python爬虫学习==>第七章:urllib库的基本使用方法
学习目的: urllib提供了url解析函数,所以需要学习正式步骤 Step1:什么是urllib urllib库是Python自带模块,是Python内置的HTTP请求库 包含4个模块: >& ...
- python--爬虫入门(七)urllib库初体验以及中文编码问题的探讨
python系列均基于python3.4环境 ---------@_@? --------------------------------------------------------------- ...
- urllib库初体验以及中文编码问题的探讨
提出问题:如何简单抓取一个网页的源码 解决方法:利用urllib库,抓取一个网页的源代码 ------------------------------------------------------- ...
- Python爬虫入门 Urllib库的基本使用
1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它是一段HTML代码,加 JS.CSS ...
- Python爬虫入门:Urllib库的基本使用
1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它 是一段HTML代码,加 JS.CS ...
随机推荐
- SpringBoot整合Flyway(数据库版本迁移工具)
简介 在团队开发当中,有可能每个人都是使用自己本地的数据库.当数据库的表或者字段更新时,往往需要告知团队的其他同事进行更新. Flyway数据库版本迁移工具,目的就是解决该问题而诞生的(我自己想的). ...
- Java 第十一届 蓝桥杯 省模拟赛 凯撒密码加密
凯撒密码加密 题目 问题描述 给定一个单词,请使用凯撒密码将这个单词加密. 凯撒密码是一种替换加密的技术,单词中的所有字母都在字母表上向后偏移3位后被替换成密文.即a变为d,b变为e,-,w变为z,x ...
- java实现迷宫走法
** 迷宫走法** 迷宫问题 对于走迷宫,人们提出过很多计算机上的解法.深度优先搜索.广度优先搜索是使用最广的方法.生活中,人们更愿意使用"紧贴墙壁,靠右行走"的简单规则. 下面的 ...
- java实现第五届蓝桥杯大衍数列
大衍数列 中国古代文献中,曾记载过"大衍数列", 主要用于解释中国传统文化中的太极衍生原理. 它的前几项是:0.2.4.8.12.18.24.32.40.50 ... 其规律是:对 ...
- TZOJ 车辆拥挤相互往里走
102路公交车是crq经常坐的,闲来无聊,他想知道最高峰时车上有多少人,他发现这辆车只留一个门上下人,于是他想到了一个办法,上车时先数一下车上人员数目(crq所上的站点总是人不太多),之后就坐在车门口 ...
- (数据科学学习手札86)全平台支持的pandas运算加速神器
本文示例代码已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 随着其功能的不断优化与扩充,pandas已然成为 ...
- 带你学够浪:Go语言基础系列 - 8分钟学控制流语句
★ 文章每周持续更新,原创不易,「三连」让更多人看到是对我最大的肯定.可以微信搜索公众号「 后端技术学堂 」第一时间阅读(一般比博客早更新一到两篇) " 对于一般的语言使用者来说 ,20% ...
- 【Java Spring Cloud 实战之路】添加一个SpringBootAdmin监控
0. 前言 在之前的几章中,我们先搭建了一个项目骨架,又搭建了一个使用nacos的gateway网关项目,网关项目中并没有配置太多的东西.现在我们就接着搭建在Spring Cloud 微服务中另一个重 ...
- jar 反编译工具
luyten windows版本的 链接:https://pan.baidu.com/s/1hp6gyvJSj_4h60dk5AZejA 密码:c4u7 之所以推荐它,是因为它能避免普通的编译工具jd ...
- 2019-02-07 selenium...
今天是超级郁闷的一天 看教程 下了mysql-----配置-----不会----查资料------2小时后 mongodb-----配置------不会------查资料------1小时后 然后是各 ...