python2网页采集案例

本文介绍了使用Python的urllib2库进行网页数据抓取的方法,包括简单的直接抓取、带参数抓取及带cookie抓取等多种场景。针对不同需求如需要cookie支持、使用代理等提供了详细的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.简单直接采集

import urllib2
response=urllib2.urlopen('http://www.xxx.com')
#获取状态吗,如果是200表示获取成功
print response.getcode()
#读取内容
cont=response.read()
print len(cont)

2.带参数采集
import urllib2
#创建Request对象
request=urllib2.Request('http://www.xxx.com')
#添加数据
request.add_data('a','1')
#添加http的header
request.add_header('User-Agent','Mozilla/5.0')
#发送请求获取结果
response=urllib2.urlopen(request)
print response.getcode()

3.带cookie采集
import urllib2,cookielib
#创建cookie容器
cj=cookielib.CookieJar()
#创建1个opener
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
#给urllib2安装opener
urllib2.install_opener(opener)
#使用带有cookie的urllib2访问网页
response=urllib2.urlopen('http://www.xxx.com')
print cj
print response.getcode()

print response.read()


特殊采集:
有的采集需要cookie的支持
有的采集需要proxy代理
有的采集需要https加密方式
有的采集是需要做Redirect跳转

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值