Python爬虫----网页下载器和urllib2模块及对应的实例

网页下载器:将互联网上URL对应的网页下载到本地的工具,是爬虫的核心组件


urllib2下载网页的三种方法

对应实例代码如下:

#coding:utf8

import urllib2  
     
url =  'http://www.baidu.com'

print '第一种方法 --> 直接请求 '
response1 = urllib2.urlopen(url)  
      
#获取状态码,如果是200表示获取成功  
print response1.getcode()  
      
# 获取读取到的内容的长度 
print len(response1.read() )

第一种方法 --> 直接请求
200
4305

#coding:utf8

import urllib2  
     
url =  'http://www.baidu.com'

print '第二种方法:'
#创建Request对象
request= urllib2.Request(url)

#添加http的header
request.add_header('User-Agent' , 'Mozilla/5.0')

# 发送请求获取结果
response2 = urllib2.urlopen(request)

print response2.getcode()
print len(response2.read())

第二种方法:
200
4305

#coding:utf8

import urllib
import urllib2
import cookielib 
     
url =  'http://www.baidu.com'

print '第三种方法:'

#创建cookie容器
cj = cookielib.CookieJar()

#创建1个opener
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

# 给urllib2安装opener
urllib2.install_opener(opener)

# 使用带有cookie的urllib2访问网页
response3 = urllib2.urlopen(url)

print response3.getcode()
print cj
print response3.read()
第三种方法:
200
<CookieJar[]>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
......

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值