python爬虫-12-24

编码的问题算是解决了一部分了。。我在解码时使用page.decode('gb2312','ignore'),将无法解码的东西变成?,虽然爬下来的网页,关于中文部分全是乱码,不过起码可以正常提取url了。

# -*- coding: gb2312 -*-
import urllib.request
def getContent(url): 
  f=urllib.request.urlopen(url)
  page=f.read()
  page=page.decode('gbk','ignore');
  return page

def getUrl(page):
  start_link=page.find('<a href=')
  start_quote=page.find('"',start_link)
  end_quote=page.find('"',start_quote+1)
  url=page[start_quote+1:end_quote]
  page=page[end_quote:]
  return url

def storefile(url,page):
  f=open('url','w')
  f.write(page)
  f.close()

def fetchwidth(url,width,deepth):
  i=0
  page=getContent(url)
  while(i<width):
    start_link=page.find('<a href=')
    start_quote=page.find('"',start_link)
    end_quote=page.find('"',start_quote+1)
    url=page[start_quote+1:end_quote]
    s=getContent(url)
    fetchdepth(url,deepth)
    storefile(url,s)
    page=page[end_quote:]
    i=i+1 

def fetchdepth(url,deepth):
  i=0
  page=getContent(url)
  while(i<deepth):
    start_link=page.find('<a href=')
    start_quote=page.find('"',start_link)
    end_quote=page.find('"',start_quote+1)
    url=page[start_quote+1:end_quote]
    page=getContent(url)
    storefile(url,page)
    i=i+1 
    

fetchwidth('http://www.baidu.com',2,2)

以上是暂时完成的一部分代码,算是原型模型中的核心功能了,爬取代码是可以的,而且可以自己定义深度和广度。

不过离要求还差一些。

首先时存代码的那一部分,我目前还想不到什么方法可以将url转换为str作为文件名来存储文档。

还有一个问题就是多线程的问题。

当然关于编码的问题还是存在的,这个问题迟早得解决。。。

posted @ 2012-12-24 20:00  derekDoMo  阅读(233)  评论(0编辑  收藏  举报