python编写爬虫获取区域代码-递归获取所有子页面

上一篇文章用htmlparser写了一个java的获取区域的爬虫,觉得太笨重。发现python也可以实现这个功能。

这里就简单写一个用python3写的小爬虫例子

功能目标:对指定网站的所有区域信息进行筛选,并保存到文本中

思路:1、定义一个队列,初始向队列中put一个地址

   2、判断队列是否为空,不为空调用getURL函数,为空则结束

   3、getURL获取URL链接的内容,并用beautifulSoup(第三方需要单独安装,可百度)匹配a链接

   4、对匹配的内容进行字符串拼接,调用text_create保存成文本

声明:这个只是一个DEMO,可以参考学习使用,所以逻辑不是很严谨,大家勿喷。

#coding:utf-8
import urllib.request
import sys,operator
import queue
import re
import sys
from bs4 import BeautifulSoup
base = "http://www.diqudaima.com/"
lr = queue.Queue()

def text_create(name, msg):#保存文件,传入文件名与内容
    desktop_path = '/Users/wuhao/Desktop/python/'    
    full_path = desktop_path + name + '.txt' 
    file = open(full_path,'w')             
    file.write(msg) 
    file.close() 
    print('Done :',name)

def getURL(url):
	try:
		req = urllib.request.Request(url)
		response = urllib.request.urlopen(req)
		the_page = response.read().decode("GBK")
		soup = BeautifulSoup(the_page, 'html.parser')
		data=soup.select("div ul li a")#获取a链接
		body =''
		if len(data)>0:
			for html_tag in data:
				print("title :  "+html_tag.string)
				print(base+html_tag['href'][1:])
				body+=html_tag.string
				body+='\n'
				lr.put_nowait(base+html_tag['href'][1:])
		else:
			data=soup.select("div ul li")
			for html_tag in data:
				print("title :  "+html_tag.string)
				body+=html_tag.string
				body+='\n'
		mode = re.compile(r'\d+')
		print (mode.findall(url))
		if len(mode.findall(url))>0:
			text_create(mode.findall(url)[0],body)
	except:#因为可能出现TimeoutError等异常,这里捕获并重新放入队列中
		print("链接超时,未处理链接:",lr.qsize())
		lr.put_nowait(url)
	else:
		print("未处理链接:",lr.qsize())

if __name__ == "__main__":
	url="http://www.diqudaima.com/zhejiang/hangzhoushi/"
	lr.put_nowait(url)
	while not lr.empty():
		vistorUrl =lr.get_nowait()
		print ("访问链接:"+vistorUrl)
		getURL(vistorUrl)
		

运行结果:



发布了20 篇原创文章 · 获赞 23 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/hdu09075340/article/details/74202339
今日推荐