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作为文件名来存储文档。

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

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

转载于:https://www.cnblogs.com/derekDoMo/archive/2012/12/24/2831501.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值