《python爬虫》学习笔记:urllib2库的使用

最简单的爬虫代码

import  urllib2
response=urllib2.urlopen("http://www.baidu.com")
print response.read()

上面的等价代码

#encoding=utf-8
import urllib2
request=urllib2.Request("http://www.baidu.com")#构造一个request对象实例
response=urllib2.urlopen(request)
print response.read()

POST和GET的使用

先看post提交数据的方法,如下:

#encoding=utf-8
#post 方式传送数据
import urllib
import urllib2
values={'username':'154943046@qq.com','password':'xxxx'}
data=urllib.urlencode(values)#将提交的字典编码
url="https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn"
request=urllib2.Request(url,data)
response=urllib2.urlopen(request)
print response.read()

get方式的传送数据

#encoding=utf-8
import urllib
import urllib2
#python中字典的另外一种写法
values={}
values["username"]="154943046@qq.com"
values["password"]="XXXX"
data=urllib.urlencode(values)
url="https://passport.csdn.net/account/login"
geturl=url+"?"+data#get方式传送数据
print geturl
request=urllib2.Request(geturl)

response=urllib2.urlopen(request)
print response.read()

设置请求头

#encoding=utf-8
#设置请求头
import urllib
import urllib2
user_agent="Mozilla/5.0 (Windows NT 6.1)"
referer="http://www.zhihu.com/"
header={"User-Agent":user_agent,"Referer":referer}
url="http://www.zhihu.com/"
values={"username":"wuranghao","password":"xxxx"}
data=urllib.urlencode(values)
request=urllib2.Request(url ,data ,header)
response=urllib2.urlopen(request)
print response.read()

URLError和HTTPError

#encoding=utf-8
#访问错误的URL的抛异常的处理
#首先解释下URLError可能产生的原因:
#   网络无连接,即本机无法上网
#   连接不到特定的服务器
#   服务器不存在

import urllib2
url="http://wuranghao.com"
request=urllib2.Request(url)
try:
    response=urllib2.urlopen(request)
except urllib2.URLError,e:
    print e.reason  #输出  [Errno 11004] getaddrinfo failed
#encoding=utf-8
#HTTPError的讲解:HTTPError是URLError的子类,在你利用urlopen方法发出一个请求时,
#服务器上都会对应一个应答对象response,其中它包含一个数字”状态码”。
import urllib2
url="http://www.xingjiakmite.com"
request=urllib2.Request(url)
try:
    response=urllib2.urlopen(request)
except urllib2.HTTPError,e:
    if hasattr(e,"code"):
        print e.code
    if hasattr(e,"reason"):
        print e.reason
except urllib2.URLError,e:
    if hasattr(e,"reson"):
        print e.reason
else:
    print "OK"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值