urllib 学习一
说明:Urllib 是一个python用于操作URL的模块
python2.x ----> Urillib/Urllib2
python3.x ----> Urllib
一、变动说明:
python2 中的Urllib和Urllib2 在python3 中合并为Urllib库,使用方法变动如下:
python2 python3
import urllib2 --------------> import urllib.request/urllib.error
import urllib --------------> import urllib.request/urllib.error/urllib.parse
import urlparse --------------> import urllib.parse
urllib2.open --------------> urllib.request.urlopen
urllib.urlencode --------------> urllib.parse.urlencode
urllib.quote --------------> urllib.request.quote
cookielib.CookieJar --------------> http.CookieJar
urllib2.Request --------------> urllib.request.Request
二、使用Urllib爬取网页(python3)
urlopen方法
#导入模块:
import urllib.request #打开网页,并将打开的内容赋给变量(urllopen):
content_text = urllib.request.urlopen('http://blog.51cto.com') #读取网页内容:
content_text.read() / content_text.readlines()
content_text.readline()
content_text
.getcode() ###打印状态码
.url() ##打印url地址
.getheaders() ##打印头信息
.info() ##打印响应信息
print (dir(content_text)) ##打印所有方法
使用write方法写入到文件
file_save = open('51cto.html',"wb") ##以二进制方式写入
file_save.write(content_text.read())
file_save.close()
使用urltrieve函数写入
#使用urllib.request.urltrieve函数写入 urllib.request.urlretrieve(url,filename='本地文件地址')
#示例
urllib.request.urlretrieve('http://blog.51cto.com',filename='2.html')
urlretrieve函数解析
urltrive函数,将远程数据下载到本地
urlretrieve(url, filename=None, reporthook=None, data=None)
参数 finename 指定了保存本地路径(如果参数未指定,urllib会生成一个临时文件保存数据。)
参数 reporthook 是一个下载状态报告。
参数 data 指 post 到服务器的数据,该方法返回一个包含两个元素的(filename, headers)元组,filename 表示保存到本地的路径,header 表示服务器的响应头。
urlretrieve执行过程中会产生缓存,可用 urlcleanup()进行清除 urllib.request.urlcleanup()
对网址进行编码解码:
编码:
urllib.request.quote("http://blog.51cto.com") ----------> http%3A//blog.51cto.com 解码:
urllib.request.unquote("http%3A//blog.51cto.com")
三、模拟浏览器headers属性
浏览器headers信息

urllib.request.Request方法
使用爬虫模拟浏览器头信息:
A、urllib.request.build_opener()方法
headers = ("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3107.4 Safari/537.36")
opener = urllib.request.build_opener() ###创建自定义opener对象
opener.addheaders = [headers] ###添加headers信息
data = opener.open(url) ##模仿浏览器访问网站
B、urllib.request.Request 方法的add_header()属性
url = "http://blog.51cto.com"
req = urllib.request.Request(url) #创建一个request对象
req.add_header("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3107.4 Safari/537.36")
#或者这样写
headers = {"User-Agent","...."}
req = urllib.request.Request(url,headers=headers)
data = urllib.request.urlopen(req)
超时设置:
import urllib.request
urllib.request.urlopen(url,timeout=1)
有时候访问get请求(搜索)的时候会遇到编码问题,需要用urllib.request.quote()对关键字进行编码,然后在构造完整的url才能进行请求
如:
url=’http://xxx.com/search?wd=..’
key=’要搜索的关键词’
key_code=urllib.request.quote(key)
url_all = url+key_code
urllib.request.urlopen(url_all)
post请求(流程方法)
A、 设置好url网址 B、 构建表单数据,并用urllib.parse.urlencode对数据进行编码 C、 创建requset对象,参数包括url地址和要传递的数据 D、 添加头信息(add_header()),模拟浏览器 E、 使用urllib.request.urlopen()打开对应的request对象,完成信息传递 F、 后续处理(网页内容的处理和存储等)
代码实现:
B、需要分析网页源代码或f12查看属性,查看要传入值的属性,构建字典:
values = {key1:v1,key2:v2}
post_data = urllib.parse.urlencode(values).encode(‘utf-8’)
C、req = urllib.request.Request(url,post_data) ##创建request对象
D、req.add_header(‘User-Agent’,…) #添加头信息
E、data = urllib.request.urlopen(req) ##打开网页
代理服务器设置
http://www.xicidaili.com/ ##查找代理服务器
代码实现
def use_proxy(proxy_addr,url):
import urllib.request
proxy = urllib.request.ProxyHandler({'http':proxy_addr}) #设置对应的代理服务器信息
#对于一个代理ip列表、可以写成
import random
proxy = urllib.request.ProxyHandler({"http":random.choice(ip列表)})
或换个方式
proxy_info = { 'host' : 'proxy.myisp.com', 'port' : 3128 }
proxy_support = urllib.request.ProxyHandler({"http" : "http://%(host)s:%(port)d" % proxy_info})
opener = urllib.request.build_opener(proxy,urllib.request.HTTPHandler) #创建自定义opener对象
urllib.request.install_opener(opener) #创建全局默认的oper对象
data = urllib.request.urlopen(url).read().decode(‘utf-8’)
return data
proxy_addr = 'xxx.xxx.xxx.xxx:7777'
data = use_proxy(proxy_addr,url)
print (len(data))
如果代理ip不能用会提示:
·
DebugLog
A、使用urllib.request.HTTPHandler() 和 urllib.request.HTTPSHandler() 将debuglevel 设置为1 B、使用urllib.request.build_opener() 创建自定义的opener对象,并设置以上为参数 C、用urllib.request.install_opener() 创建全局默认的opener对象 D、open
代码实现:
import urllib.request httpd = urllib.request.HTTPHandler(debuglevel=1)
httpsd = urllib.request.HTTPSHandler(debuglevel=1)
opener = urllib.request.build_opener(httpd,httpsd)
urllib.request.install_opener(opener)
data = urllib.request.urlopen(url)

异常处理:
URLError
HTTPrror

最终版

urllib 学习一的更多相关文章
- python 3.x urllib学习
urllib.request import urllib.request as ur url='http://ie.icoa.cn' user_agent = 'Mozilla/4.0 (compat ...
- urllib 学习二
编码解码: python2 用法: urllib.urlencode() 编码 urlparse.parse_qs() 解码 python3 用法: urllib.parse.urlencode() ...
- python的urllib学习
1.基本方法 urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=Fals ...
- python的httplib、urllib和urllib2的区别及用
慢慢的把它们总结一下,总结就是最好的学习方法 宗述 首先来看一下他们的区别 urllib和urllib2 urllib 和urllib2都是接受URL请求的相关模块,但是urllib2可以接受一个Re ...
- python内建模块发起HTTP(S)请求
一.Python2 httplib 简介:httplib实现了HTTP和HTTPS的客户端协议,一般不直接使用,在python更高层的封装模块中(urllib,urllib2)使用了它的http实现. ...
- Python3学习笔记(urllib模块的使用)转http://www.cnblogs.com/Lands-ljk/p/5447127.html
Python3学习笔记(urllib模块的使用) 1.基本方法 urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, ...
- Python 学习之urllib模块---用于发送网络请求,获取数据(2)
接着上一次的内容. 先说明一下关于split()方法:它通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串(把一个字符串分割成很多字符串组成的list列表) 语法: ...
- python urllib基础学习
# -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' #使用python创建一个简单的WEB客户端 import urll ...
- 爬虫新手学习2-爬虫进阶(urllib和urllib2 的区别、url转码、爬虫GET提交实例、批量爬取贴吧数据、fidder软件安装、有道翻译POST实例、豆瓣ajax数据获取)
1.urllib和urllib2区别实例 urllib和urllib2都是接受URL请求相关模块,但是提供了不同的功能,两个最显著的不同如下: urllib可以接受URL,不能创建设置headers的 ...
随机推荐
- sql server对已创建的表增加属性(自动增序)
新建此表时把ID设为INT类型,然后设Identity为yes,种子为1递增就可以了.如果这张表已经建了,你在最后加一个字段叫ID,然后和上面一样操作,然后保存即可自增.(一定要设置完在保存) alt ...
- BZOJ4372烁烁的游戏——动态点分治+线段树(点分树套线段树)
题目描述 背景:烁烁很喜欢爬树,这吓坏了树上的皮皮鼠.题意:给定一颗n个节点的树,边权均为1,初始树上没有皮皮鼠.烁烁他每次会跳到一个节点u,把周围与他距离不超过d的节点各吸引出w只皮皮鼠.皮皮鼠会被 ...
- P1601 A+B Problem(高精)
原题链接 https://www.luogu.org/problemnew/show/P1601 这个题提示的很清楚,并非简单的A+B,单纯的long long型也不行(不要被样例所迷惑).因为lo ...
- springboot使用redis
1.pom文件中引入 spring-boot-starter-redis <dependency> <groupId>org.springframework.boot</ ...
- POI中不推荐的方法与其替代的方法
不推荐getCellType(),推荐getCellTypeEnum() if(tcell.getCellTypeEnum() == CellType.NUMERIC){ System.out.pri ...
- MT【272】更大的视野,更好的思路.
已知$f(x)=\sum\limits_{k=1}^{2017}\dfrac{\cos kx}{\cos^k x},$则$f(\dfrac{\pi}{2018})=$_____ 分析:设$g(x)=\ ...
- 【HDU - 4345 】Permutation(DP)
BUPT2017 wintertraining(15) #8F 题意 1到n的排列,经过几次置换(也是一个排列)回到原来的排列,就是循环了. 现在给n(<=1000),求循环周期的所有可能数. ...
- python学习日记(流程控制习题)
请输出1-2+3...+99除88以外的和 i = 1 sum = 0 while i <= 99: if i == 88: i = i + 1 continue else: if i%2 == ...
- [luogu2476][bzoj1079][SCOI2008]着色方案【动态规划】
题目描述 有n个木块排成一行,从左到右依次编号为1~n.你有k种颜色的油漆,其中第i种颜色的油漆足够涂ci个木块.所有油漆刚好足够涂满所有木块,即c1+c2+-+ck=n.相邻两个木块涂相同色显得很难 ...
- [HAOI2012]道路(最短路DAG上计数)
C国有n座城市,城市之间通过m条[b]单向[/b]道路连接.一条路径被称为最短路,当且仅当不存在从它的起点到终点的另外一条路径总长度比它小.两条最短路不同,当且仅当它们包含的道路序列不同.我们需要对每 ...