python抓取搜索到的url,小型爬虫

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import re
import urllib2

from BeautifulSoup import BeautifulSoup

def search(key):
	#请求搜索链接,关键字用参数key代替
	search_url='http://www.baidu.com/s?ie=UTF-8&wd=key'
	req=urllib2.urlopen(search_url.replace('key',key))
	
	#计数变量,用来记录页数
	count = 1
	
	#主循环,抓取每一页的url,直到最后一页
	while 1:
		print "\033[1;31mpage %s:\033[0m" % count
		html=req.read()
		soup=BeautifulSoup(html)
		f = open("result.txt",'a')
		
		#url在<span>...</span>中,
		content  = soup.findAll('span',attrs={'class':'g'})
		
		#对每一个对象解析
		for i in content:
			pat = re.compile("^(.+?) .*$")
                	#i为对象,所以用i.text转换为字符串
			url = re.search(pat,i.text)
			#url有可能匹配不到
			if url:
				f.write(url.group(1)+"\n")
				print url.group(1)
			else:
				next
		f.close()
		#得到“下一页”的链接。除了第一页和最后一页,其他的会有2个元素。第一个为上一页,第二个为下一页。
		#这里取倒数第一个元素
              	next_page='http://www.baidu.com'+soup('a',{'href':True,'class':'n'})[-1]['href']
		#最后一页只有一个元素,倒数第一个是“上一页”,所以判断一下,如果只有一个元素,并且不是第一页就结束。
		#否则可能会造成死循环
		if count >1 and len(soup('a',{'href':True,'class':'n'}))==1:
			print "\033[1;31mcomplete!\033[0m"
			break
		#不是最后一页就继续
		else:
			req=urllib2.urlopen(next_page)
			count += 1

if __name__=='__main__':
	key = "hello world!"
	search(key)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值