urllib和urllib2常用方法
2015-11-04 17:21
204 查看
在写爬虫时常常用法一些方法,这里我简单做一下归纳
一部分:访问服务器
1.html=urllib2.urlopen("http://www.baidu.com")打开网页,中间包含了一个request请求
2.content=html.read()将上面内容打开网页内容读取下来
3.request = urllib2.Request(url, values, headers)
发送特定请求,post请求,values和headers均是字典,但是values需要编码,而headers不需要编码
4.html=urllib2.urlopen(request)和1的内容基本相似
5.urllib.urlencode(values)使用request发送请求之前还需要将数据进行编码,注意这个是urllib而不是urllib2
6.urllib2.ProxyHandler()设置代理服务其进行访问网站,用处不用多说
importurllib2
enable_proxy =True
proxy_handler=
urllib2.ProxyHandler({"http":
'http://some-proxy.com:8080'})
null_proxy_handler =urllib2.ProxyHandler({})
ifenable_proxy:
opener=
urllib2.build_opener(proxy_handler)
else:
opener=
urllib2.build_opener(null_proxy_handler)
urllib2.install_opener(opener)
功能是enable_proxy为true则用代理服务器,否则设置代理服务其为空,就是本地主机访问了
2.HTTPError是上面异常子类,报错时会显示各种状态吗,如404,401
根据经验,父类一般写在子类下面,看下面代码
importurllib2
req=
urllib2.Request(“www.baidu.com”)
try:
urllib2.urlopen(req)
except urllib2.HTTPError,e:
printe.code
except urllib2.URLError,e:
printe.reason
else:
print"OK"
1.opener,urlopen()是一个默认的opener,当需要使用cookie时则需要新建opener,可以实现模拟登陆服务器功能
2.cookielib功能非常强大CookieJar、FileCookieJar、MozillaCookieJar、LWPCookieJar。他们之间的关系是CookieJar
—-派生—->FileCookieJar —-派生—–>MozillaCookieJar和LWPCookieJar
3.将cookieJar获取cookie功能,cookie变量值是保存在下面例子的cookie变量中的
#coding=utf-8
import urllib2
import cookielib
cookie=cookielib.CookieJar()
hander=urllib2.HTTPCookieProcessor(cookie)
opener=urllib2.build_opener(hander)
response=opener.open("http://www.baidu.com")#打开网页后才能拥有cookie值
for item in cookie:
print "Name= "+item.name
print "value= "+item.value
4.强cookie值保存在文件中,保存的cookie是经过格式化的,如果将上面的name和value写在文件里会很乱
这时候要使用FileCookieJar()子类MozillaCookieJar
#coding=utf-8
import urllib2
import cookielib
filename="C:\Users\Administrator\Desktop\wanlei\wanleicookie.txt"
cookie=cookielib.MozillaCookieJar(filename)
hander=urllib2.HTTPCookieProcessor(cookie)
opener=urllib2.build_opener(hander)
response=opener.open("http://www.baidu.com")
cookie.save(ignore_discard=True,ignore_expires=True)
save函数参数ignore_discard的意思是即使cookies将被丢弃也将它保存下来,ignore_expires的意思是如果在该文件中
cookies已经存在,则覆盖原文件写入。
5.从cookie文件夹在cookie
#coding=utf-8
import urllib2
import cookielib
cookie=cookielib.MozillaCookieJar()
cookie.load("C:\Users\Administrator\Desktop\wanlei\cookie.txt")
req=urllib2.Request("http://www.baidu.com")
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
response=opener.open(req)
print response.read()
6.下面是个例子,登陆我们学校的服务器
def login():
number="2014241177"
pwd="*********"
data={"email":email,"passworld":pwd}
#将post消息化成可以让服务器编码的方式
post_data=urllib.urlencode(data)
cj=cookielib.CookieJar()
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
headers={"User-agent":"Mozilla/4.0 (compatible;MSIE 6.0; Windows NT 5.1)"}
website="http://myportal.sxu.edu.cn/login.portal"
req=urllib2.Request(website,post_data,headers)
content=opener.open(req)
print content.read()
login()
http://python.jobbole.com/81359/
一部分:访问服务器
1.html=urllib2.urlopen("http://www.baidu.com")打开网页,中间包含了一个request请求2.content=html.read()将上面内容打开网页内容读取下来
3.request = urllib2.Request(url, values, headers)
发送特定请求,post请求,values和headers均是字典,但是values需要编码,而headers不需要编码
4.html=urllib2.urlopen(request)和1的内容基本相似
5.urllib.urlencode(values)使用request发送请求之前还需要将数据进行编码,注意这个是urllib而不是urllib2
6.urllib2.ProxyHandler()设置代理服务其进行访问网站,用处不用多说
importurllib2
enable_proxy =True
proxy_handler=
urllib2.ProxyHandler({"http":
'http://some-proxy.com:8080'})
null_proxy_handler =urllib2.ProxyHandler({})
ifenable_proxy:
opener=
urllib2.build_opener(proxy_handler)
else:
opener=
urllib2.build_opener(null_proxy_handler)
urllib2.install_opener(opener)
功能是enable_proxy为true则用代理服务器,否则设置代理服务其为空,就是本地主机访问了
二:异常处理
1.urllib2.URLError访问网页不存在2.HTTPError是上面异常子类,报错时会显示各种状态吗,如404,401
根据经验,父类一般写在子类下面,看下面代码
importurllib2
req=
urllib2.Request(“www.baidu.com”)
try:
urllib2.urlopen(req)
except urllib2.HTTPError,e:
printe.code
except urllib2.URLError,e:
printe.reason
else:
print"OK"
三:cookie使用
ccokie:Cookie,指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据,urllib2可以保存我们的cookie数据,因为cookies一般是是保存在浏览器的,这里urllib2充当浏览器功能1.opener,urlopen()是一个默认的opener,当需要使用cookie时则需要新建opener,可以实现模拟登陆服务器功能
2.cookielib功能非常强大CookieJar、FileCookieJar、MozillaCookieJar、LWPCookieJar。他们之间的关系是CookieJar
—-派生—->FileCookieJar —-派生—–>MozillaCookieJar和LWPCookieJar
3.将cookieJar获取cookie功能,cookie变量值是保存在下面例子的cookie变量中的
#coding=utf-8
import urllib2
import cookielib
cookie=cookielib.CookieJar()
hander=urllib2.HTTPCookieProcessor(cookie)
opener=urllib2.build_opener(hander)
response=opener.open("http://www.baidu.com")#打开网页后才能拥有cookie值
for item in cookie:
print "Name= "+item.name
print "value= "+item.value
4.强cookie值保存在文件中,保存的cookie是经过格式化的,如果将上面的name和value写在文件里会很乱
这时候要使用FileCookieJar()子类MozillaCookieJar
#coding=utf-8
import urllib2
import cookielib
filename="C:\Users\Administrator\Desktop\wanlei\wanleicookie.txt"
cookie=cookielib.MozillaCookieJar(filename)
hander=urllib2.HTTPCookieProcessor(cookie)
opener=urllib2.build_opener(hander)
response=opener.open("http://www.baidu.com")
cookie.save(ignore_discard=True,ignore_expires=True)
save函数参数ignore_discard的意思是即使cookies将被丢弃也将它保存下来,ignore_expires的意思是如果在该文件中
cookies已经存在,则覆盖原文件写入。
5.从cookie文件夹在cookie
#coding=utf-8
import urllib2
import cookielib
cookie=cookielib.MozillaCookieJar()
cookie.load("C:\Users\Administrator\Desktop\wanlei\cookie.txt")
req=urllib2.Request("http://www.baidu.com")
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
response=opener.open(req)
print response.read()
6.下面是个例子,登陆我们学校的服务器
def login():
number="2014241177"
pwd="*********"
data={"email":email,"passworld":pwd}
#将post消息化成可以让服务器编码的方式
post_data=urllib.urlencode(data)
cj=cookielib.CookieJar()
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
headers={"User-agent":"Mozilla/4.0 (compatible;MSIE 6.0; Windows NT 5.1)"}
website="http://myportal.sxu.edu.cn/login.portal"
req=urllib2.Request(website,post_data,headers)
content=opener.open(req)
print content.read()
login()
http://python.jobbole.com/81359/
相关文章推荐
- 关于 Java Collections API 您不知道的 5 件事--转
- js问题学习
- 分组查询之牛刀小试!
- Hadoop 2.6.2 完全分布式环境搭建
- 关于 java.util.concurrent 您不知道的 5 件事--转
- 简单的介绍Thread与Handler的原理
- Asp.net 日历控件
- LeetCode OJ:Linked List Cycle II(循环链表II)
- 初创团队的精细化分析和 Growth Hacking
- Android设计模式——Builder模式
- ubunto命令大全
- 编写一个函数,可以左旋字符串中k个字符
- 常见标签之头标签
- mac基本操作
- Servlet 文件上传
- from里button会提交表单
- Nginx学习笔记
- 到底什么是 Growth Hacking?
- 解决python在windows上运行弹出cmd窗口(dos窗口)
- 详解Swift语言中的类与结构体