Extract HTML Title, Description, Keywords(Chilkat/Python学习二 )

本文介绍如何使用Chilkat库在Python中实现基本的网页爬取功能,并解决中文乱码问题。通过实例演示了如何获取指定网站的页面标题、描述及关键词。
 
既然自己要学习 Chilkat,那就接着写他的东西吧;

好了,开始吧!
首先你要学习这篇内容你必须了解python语法,python很简单,但是做的事不简单,这也是我学习他的原因;还有你必学安装
Chilkat,具体细节去看我的

 Getting Started Spidering a Site使用Chilkat(python)练习的一个爬虫(from :http://www.example-code.com)

http://blog.youkuaiyun.com/Xiao_Qiang_/archive/2008/08/23/2820293.aspx


一、源码
  1. from extra import  chilkat
  2. # The Chilkat Spider component/library is free.
  3. spider = chilkat.CkSpider()

  4. # The spider object crawls a single web site at a time.  As you'll see
  5. # in later examples, you can collect outbound links and use them to
  6. # crawl the web.  For now, we'll simply spider 10 pages of chilkatsoft.com
  7. spider.Initialize("http://www.vtchina.com/")

  8. # Add the 1st URL:
  9. spider.AddUnspidered("http://www.vtchina.com/")


  10. # Begin crawling the site by calling CrawlNext repeatedly.

  11. for i in range(0,10):

  12.     success = spider.CrawlNext()
  13.     if (success == True):
  14.         # Show the URL of the page just spidered.
  15.         print spider.lastUrl()

  16.         # The HTML META keywords, title, and description are available in these properties:
  17.         print spider.lastHtmlTitle()
  18.         
  19.         info = spider.lastHtmlDescription()
  20.         HtmlDescription = unicode(info,"utf-8")
  21.         print HtmlDescription
  22.         print spider.lastHtmlKeywords()

  23.         # The HTML is available in the LastHtml property
  24.     else:
  25.         # Did we get an error or are there no more URLs to crawl?
  26.         if (spider.get_NumUnspidered() == 0):
  27.             print "No more URLs to spider"
  28.         else:
  29.             print spider.lastErrorText()

  30.     # Sleep 1 second before spidering the next URL.
  31.     spider.SleepMs(1000)
注意我这里是爬网站http://www.vtchina.com/,是一个中文的网站,程序执行下来,语句
print spider.lastHtmlTitle() 输出的是乱码,处理方法到调用chilkatPython的目录下,先把chilkat.cpy修改一下文件名,反正不要是 chilkat就可以了,防止调用他而不去调用 chilkat.py;然后我们再修改 chilkat.py;在 chilkat.py中 找到  def lastHtmlTitle(*args):函数,修改为
  1.     def lastHtmlTitle(*args):
  2.         utfchar = _chilkat.CkSpider_lastHtmlTitle(*args)
  3.         info = unicode(utfchar,"utf-8")
  4.         return info
这样输出的就不是乱码了。

由于是很入门的例子,代码没啥具体可说的,就是取页面title的功能。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值