关于爬虫Demo的一点补充

这篇博客补充了爬虫Demo的不足,包括DNS服务器在下载URL中的作用,如何优化URL队列的深度遍历问题,以及介绍了urllib2库的强大功能,如设置Header、模拟cookies、代理等。还提到了urlopen函数的使用及其返回对象的方法。
摘要由CSDN通过智能技术生成

上一篇简单的Demo确实实现了一些爬虫的功能。但是距真正的搜索引擎爬虫确实想去甚远。
1.首先下载URL时,大多是维护一个DNS服务器,找到相应的IP在进行下载网页。
2.维护URL队列时,上篇程序属于纵向的深度遍历,所以维护队列会越来越大,这算是比较大的bug了。解决方法起线程,或者每个页面只抓取一个URL。
3,关于URL抓取和种子URL写的也比较简陋,好吧,原谅他只是个Demo。

urllib2的库非常强大加入Header或者模仿cookies设置proxy等等。。。

先来说说urlopen()这个函数:

urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]])

Open the URL url, which can be either a string or a Request object.data may be a string specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data;

urlopen的返回值是个类文件对象,我们可以用read( ), info( ), getcode( ), geturl( )。

# -*- coding: utf-8 -*-
import urllib2

page = urllib2.urlopen("http://www.chinaz.com/")    #函数返回类文件对象
html = page.read()  #可以使用read(),readline(), readlines()对文件进行读取
page.close()
print html    #输出文件对象的内容
print page.info()   #输出头部信息
print page.getcode()    #输出错误码
print page.geturl()    #输出请求的URL

模拟User-Agent的两种方式:

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = {'User-Agent': user_agent}
req = urllib2.Request(myUrl, headers=headers)
myResponse = urllib2.urlopen(req)
req = urllib2.Request(url)
req.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT')
r = urllib2.urlopen(req)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值